Use external variable in array_filter
Solution 1:
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:
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:
Because your closure function can't see $id
. You need the use
keyword:
$foo = array_filter($bar, function($obj) use ($id) {