Search code examples
phparraysfilteringintersectionwhitelist

Filter an array of objects to keep objects with a specific property value found in a flat, whitelist array


I have this multidimensional array $currencies:

$currencies = array ( 
    0 => (object) array( 'name' => 'algo', 'fullName' => 'Algorand'), 
    1 => (object) array( 'name' => 'ardr', 'fullName' => 'Ardor'), 
    2 => (object) array( 'name' => 'eth', 'fullName' => 'Eth')
);

And I want to keep only the objects with a name that is in this array:

$filter = ["eth", "algo"];

I did this, but it doesn't work.

$currenciesFiltered = array_filter(
    $currencies,
    function ($value) use ($filter) {
        return in_array($value['name'], $filter);
    }
);

Where is my mistake?


Solution

  • According to the error output:

    Uncaught Error: Cannot use object of type stdClass as array in [...][...]:13
    

    You are casting the array to an object, but then trying to use it as an array later. When you remove the (object) casting, it works just as you are expecting.

    If you must cast to an object, do it after the filter.