Harrison Harrison - 7 months ago 17
PHP Question

laravel undefined variable, array_where

private function delete_read($id)
{
$unread = unserialize(Auth::user()->unread);

if (in_array($id, $unread))
{
$new = array_where($unread, function ($key, $value) {
return $value != $id;
});

dd($new);
}


}


I'm trying to delete read post from an unread posts list. The above codes give me an
Undefined variable: id
error, which refers to this line of code:
return $value != $id;


So my question is how to pass variables into
array_where
method?

BTW, is there any better way to delete given elements from an array, other than
unset
? Or would
unset
be better than my
array_where
approach?

Thanks.

Answer

Because $id was defined outside of the callback function you pass into array_where() this variable is out of scope and won't be available by default. However, you can try the use keyword to force $id to be in scope:

if (in_array($id, $unread))
{
    $new = array_where($unread, function ($key, $value) use ($id) {
        return $value != $id;
    });

    dd($new);
}
Comments