Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable inside PHP array_filter [duplicate]

this could be a very silly question but I just can't understand how PHP scope is working on this piece of code:

$leagueKey = 'NFL';
$response['response'] = array_filter($response['response'], function($tier){
    return ($tier['LeagueKey'] === $leagueKey ? true : false);
});

When I run that, I get an "Undefined variable: leagueKey" exception. On the other hand, this works perfectly well:

$response['response'] = array_filter($response['response'], function($tier){
    return ($tier['LeagueKey'] === 'NFL' ? true : false);
});

Why can't PHP see my $leagueKey variable inside the array_filter function?

Thanks!

like image 510
Multitut Avatar asked Sep 01 '15 04:09

Multitut


2 Answers

Your $leagueKey variable is outside the scope of the anonymous function (closure). Luckily, PHP provides a very simple way to bring variables into scope - the use keyword. Try:

$leagueKey = 'NFL';
$response['response'] = array_filter($response['response'], function($tier) use ($leagueKey) {
    return $tier['LeagueKey'] === $leagueKey;
});

This is just telling your anonymous function to "use" the $leagueKey variable from the current scope.

Edit

Exciting PHP 7.4 update - we can now use "short closures" to write functions that don't have their own scope. The example can now be written like this (in PHP 7.4):

$response['response'] = array_filter(
    $response['response'], 
    fn($tier) => $tier['LeagueKey'] === $leagueKey
);
like image 91
Scopey Avatar answered Oct 13 '22 21:10

Scopey


try this

$response['response'] = array_filter($response['response'], function($tier) use ($leagueKey) {
 return ($tier['LeagueKey'] === $leagueKey ? true : false); 
}); 
like image 5
Ganesh Ghalame Avatar answered Oct 13 '22 21:10

Ganesh Ghalame