Filtering Arrays Without Using Loops in PHP

Have you ever had the need to filter through an existing array and create a new array based on your filter for your application to process? I’m sure the majority of you have, and personally I find it a bit tedious having to create a loop each time I need to filter through the data I need.

PHP has a built in function called array_filter that allows you to filter through your arrays without the need for a loop. Personally, this approach feels much cleaner to me and simpler to comprehend.


Let’s say we have an array of People, with different names and ages. For our application though, we’d want to get a list of all People age 21 or above.

First let’s create our Person class.

Now let’s create our array of people.

Now that we have our array set up. Let’s see how we may have solved this with loops.

Not very pretty right?

Now, let’s do this using our array_filter function.

This is a much cleaner approach and clearly explains it’s intent.