Use external variable in array_filter

PhpScopeArray Filter

Php Problem Overview


I've got an array, which I want to filter by an external variable. The situation is as follows:

$id = '1';
var_dump($id);
$foo = array_filter($bar, function($obj){
	if (isset($obj->foo)) {
		var_dump($id);
		if ($obj->foo == $id) return true;
	}
	return false;
});

The first var_dump returns the ID (which is dynamically set ofcourse), however, the second var_dump returns NULL.

Can anyone tell me why, and how to solve it?

Php Solutions


Solution 1 - Php

The variable $id isn't in the scope of the function. You need to use the use clause to make external variables accessible:

$foo = array_filter($bar, function($obj) use ($id) {
    if (isset($obj->foo)) {
        var_dump($id);
        if ($obj->foo == $id) return true;
    }
    return false;
});

Solution 2 - Php

Variable scope issue!

Simple fix would be :

$id = '1';
var_dump($id);
$foo = array_filter($bar, function($obj){
    global $id;
    if (isset($obj->foo)) {
        var_dump($id);
        if ($obj->foo == $id) return true;
    }
    return false;
}); 

or, since PHP 5.3

$id = '1';
var_dump($id);
$foo = array_filter($bar, function($obj) use ($id) {
    if (isset($obj->foo)) {
        var_dump($id);
        if ($obj->foo == $id) return true;
    }
    return false;
});

Hope it helps

Solution 3 - Php

Because your closure function can't see $id. You need the use keyword:

$foo = array_filter($bar, function($obj) use ($id) {

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSander KoedoodView Question on Stackoverflow
Solution 1 - PhpBarmarView Answer on Stackoverflow
Solution 2 - Phpphp-devView Answer on Stackoverflow
Solution 3 - PhpJoeView Answer on Stackoverflow