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;
}, ARRAY_FILTER_USE_KEY);

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

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!

Similar Posts

More content in PHP category