How to Use the PHP array_filter() Function to Filter by Keys?

To use the PHP array_filter() function to filter array elements by key instead of value, you can pass the ARRAY_FILTER_USE_KEY flag as the third argument to the function. This would pass the key as the only argument to the provided callback function.

For example, to filter numeric indexes in an array that has both, numeric and associative keys, you could do something like the following:

$arr = [
    'foo' => 'bar',
    1 => 'baz',
    'qux' => 22,
    3 => 123,
    'quux' => 'quuz',
];

$filteredArr = array_filter(
    $arr,
    fn ($key) => is_numeric($key),
    ARRAY_FILTER_USE_KEY
);

echo print_r($filteredArr, true); // [1 => 'baz', 3 => 123]

As you can see from the result, array keys are preserved (which may result in gaps in an indexed array, which is the case in this example). You can, however, choose to reindex the array (using array_values() for example).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.