Filtering Arrays by Keys

Posted on by Gergő D. Nagy

Usually, we filter arrays by their values. However, in some cases, it’s a need to filter array items by their keys. PHP provides the array_filter function for filtering arrays, but by default, it uses the value. Fortunately, we can pass a flag to the function that controls which parameter(s) should be passed.

$set = ['a', 'b', 'c', 'd'];

// Default
array_filter($set, function ($item) {
    return $item > 'b';

// Using keys
array_filter($set, functon ($key), {
    return $key > 1;

// Using both
array_filter($set, functon ($item, $key), {
    return  $item > 'a' && ($key % 2 === 0);

These flags can be very useful, especially when we want to use a bit more complex logic when filtering array items.

Looking for web dev job?
You can check them on Jooble.

Need a web developer? Maybe we can help, get in touch!