Filtering Arrays by Keys

PHPPosted on

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.

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

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in PHP category