Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2024 by Frank Perez.

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.

Example

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.

<?php

class Person
{
    private $name;
    private $age;

    public function __construct(string $name, int $age)
    {
        $this->name = $name;
        $this->age = $age;
    }

    public function name() : string
    {
        return $this->name;
    }

    public function age() : int
    {
        return $this->age;
    }
}

Now let’s create our array of people.

<?php

$people = [
    new Person('Frank', 29),
    new Person('Sarah', 28),
    new Person('Michael', 27),
    new Person('James', 20),
    new Person('Gabby', 21),
    new Person('Josh', 19),
];

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

<?php

$peopleOfAge = [];

foreach($people as $person) {
    if($person->age() > 20) {
        $peopleOfAge[] = $person;
    }
}

Not very pretty right?

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

<?php

$peopleOfAge = array_filter($people, function($person) {
    return $person->age() > 20;
});

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