Byte-sized functional programming: Filter first

in #php4 years ago (edited)

Often when working with a list, we only want to work with a subset of a list that meets some criteria. All non-zero values, for example, or all users that have a given role. The procedural way to do that is to stick an if statement inside a foreach loop:

foreach ($list as $value) {
    If (!meets_criteria($value)) {
        continue;
    }
    // ...
}

That mixes up the filtering with the iteration, though. It also doesn't work if we're using array_map().

Instead, we can make stripping down the list a separate operation called "filter." PHP offers the array_filter() function for that purpose.

$criteria = fn(User $user): bool => $user->hasRole('moderator');

$filtered = array_filter($users, $criteria);

Now we can work with the $filtered list, which has only the values we want. That could be a simple foreach loop, or, better, it's now ideally suited for use with array_map().


Want to know more about functional programming and PHP? Read the whole book on the topic: Thinking Functionally in PHP.


Thinking Functionally in PHP

Sort:  

Congratulations @crell! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You published more than 50 posts. Your next target is to reach 60 posts.

You can view your badges on your board And compare to others on the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @hivebuzz:

Hive Power Up Day - The first Response!
Hive Power Up Day - Let's grow together!