Sander Koedood
Sander Koedood

Reputation: 6337

Use external variable in array_filter

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?

Upvotes: 90

Views: 45236

Answers (3)

Barmar
Barmar

Reputation: 781210

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

See documentation for Anonymous functions (Example #3 "Inheriting variables from the parent scope").

Upvotes: 186

php-dev
php-dev

Reputation: 7156

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

Upvotes: 12

Joe
Joe

Reputation: 15802

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

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

Upvotes: 9

Related Questions