Undefined variable inside PHP array_filter
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
);
try this
$response['response'] = array_filter($response['response'], function($tier) use ($leagueKey) {
return ($tier['LeagueKey'] === $leagueKey ? true : false);
});
This is how the scope of all the variables work. Your anonymous function doesn't know anything about variables outside of it. This holds for all kind of functions: if you need to use a variable that is outside of a function - you pass it to the function. In this case you can't pass it anything, but if you are running PHP5.3+ you can do
function($tier) use ($leagueKey){
which will tell the function that it needs to use $leagueKey defined outside of it. If your php is lower than 5.3 you'll have to use workaround like this one:
link