Search code examples
phparraysfilteringarray-intersect

Keep array elements if key is found in flat whitelist array


How can I succeed to filter a multidimensional with a help of other array value as keys for the first array.

$multidimensional = [
    ['var1' => 'val1'],
    ['var2' => 'val2'],
    ['var3' => 'val3'],
    ['val4' => 'val4'],
];
$filter = [1, 3];

The final result should be:

$multidimensional = [
    1 => ['var2' => 'val2'],
    3 => ['val4' => 'val4']
];

It should be something similar to array_slice() or some other method. How can I easily perform such a task?


Solution

  • You can use the array_intersect_key function:

    $result = array_intersect_key($multidimensional, array_flip($filter));