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

Filtering a PHP array 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(
    fn ($key) => is_numeric($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).

Hope you found this post useful. It was published . Please show your love and support by sharing this post.