Use external variable in array_filter

Sander Koedood picture Sander Koedood · Sep 23, 2014 · Viewed 23.9k times · Source

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?

Answer

Barmar picture Barmar · Sep 23, 2014

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;
});