Thread tagged as: Question

Use a variable inside each and if


Hope someone can help with this,

I need to use $lang, inside if but it's not being picked up?

I had a similar problem last week, but that was related to $item, how do I use $lang inside if?

I can echo $lang to the page, so I know it's working up until the point I need to use it.

Here's a snippet of code:

// Hides any categories that don't have content
'each'=>function($item) {
    if (
        PerchUtil::count(perch_collection('Solutions '.$lang,[
        'category'=>$item['catPath']])) > 0) 
         return $item;


Perch Runway: 3.1.1, PHP: 7.1.12, MySQL: mysqlnd 5.0.12-dev - 20150407 - $Id: b396954eeb2d1d9ed7902b8bae237b287f21ad9e $, with PDO
Server OS: Darwin, cgi-fcgi
Installed apps: content (3.1.1), assets (3.1.1), categories (3.1.1)
App runtimes: <?php $apps_list = [ ];
PERCH_PATH: /Users/stephen/Repositories/project/cms/perch
PERCH_CORE: /Users/stephen/Repositories/project/cms/perch/core
PERCH_RESFILEPATH: /Users/stephen/Repositories/project/cms/perch/resources
Image manipulation: GD
PHP limits: Max upload 32M, Max POST 32M, Memory: 128M, Total max file upload: 32M
F1: 3b606135b33e6a102526838f4152a807
Resource folder writeable: Yes
SCRIPT_NAME: /perch/core/settings/diagnostics/index.php
REQUEST_URI: /perch/core/settings/diagnostics/
DOCUMENT_ROOT: /Users/stephen/Repositories/project/cms
HTTP_HOST: project.local
Stephen Meehan

Stephen Meehan 4 points

  • 7 months ago
Drew McLellan

Drew McLellan 2636 points
Perch Support

You need the use keyword. See here:

Ah, I thought I tried that...

Works great now. Thanks for the nudge.

// Hides any categories that don't have content
 'each'=>function($item) use(&$lang) {
                    if (
                        PerchUtil::count(perch_collection('Solutions '.$lang,[
                            'category'=>$item['catPath']])) > 0) 
                             return $item;

I also needed to pass in a second variable, this works too:

$sectors = perch_categories([
    'set' => 'sectors-'.$lang,
    'template' => $lang.'/list.html',
    // Check which items in the collection match the filter
    // This filters the items by the first category set, because the category name is in the URL
    'each' => function($item) use (&$solution_name, $lang) { // Using 2 variables in each
          $item['related_sectors'] = perch_collection('Solutions '.$lang,[
                'category' => $item['catPath'],
                'template' => 'callback.html',
                'filter' => 0, //Check the URL 
                'match' => 'contains',
                'value' => $solution_name,

          return $item;