PHP filter array by keys


Given an associative array:

$array = [
    '1' => 'One',
    '2' => 'Two',
    '3' => 'Three',
    '4' => 'Four',
];

If you want to filter the array by the keys:

$keys = [1, 3];

You can use the methods:

Filter

Using array_filter:

array_filter($array, function ($key) use ($keys) {
    return in_array($key, $keys);
}, ARRAY_FILTER_USE_KEY);

Here’s the function:

function filterArrayByKeys(array $array, array $keys): array
{
    return array_filter($array, function ($key) use ($keys) {
        return in_array($key, $keys);
    }, ARRAY_FILTER_USE_KEY);
}

Intersect

Using array_intersect_keys:

array_intersect_key($array, array_flip($keys));

Here’s the function:

function filterArrayByKeys(array $array, array $keys): array
{
    return array_intersect_key($array, array_flip($keys));
}

Demo

Repl.it:



If you enjoyed this post, please consider supporting this site!