PHP array_filter: 15 Array Filter Code Examples + Load Tests

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to use the PHP array_filter function to filter PHP Arrays Code Example

<?php 

$dogBreedsILove = ["chihuaha", "collie", "golden retriever", "terrier"];

// I need all of the retreivers in the list.
$retrievers = array_filter($dogBreedsILove, function ($breed) {
  return stripos($breed, "retriever");
}

print_r($dagBreedsILove);

PHP Array Filter Learning Path

This article is part of our large series on filtering arrays. Feel free to browse through the articles we have listed below and dig further into some unique scenarios. These articles will help you level up your PHP development skills

Filter Arrays Using PHP
PHP Arrays

Array Filter Load Testing: array_filter vs foreach loop

Array depth & executionsforeach loop timearray_filter time
Depth: 1
Executions: 1,000
0.01 seconds0.16 seconds
Depth: 1
Executions: 10,000
0.11 seconds1.16 seconds
Depth: 1
Executions: 100,000
1.09 seconds10 seconds
Depth: 1
Executions: 1,000,000
9.5 seconds1.5 minutes
Depth: 2
Executions: 1,000
0.01 seconds0.12 seconds
Depth: 2
Executions: 10,000
0.2 seconds1.3 seconds
Depth: 2
Executions: 100,000
1.4 seconds10 seconds
Depth: 2
Executions: 1,000,000
12 seconds1.7 minutes
Filtering arrays load tests

PHP Array Filtering Load Testing Performance Details

I set up a sample execution time script to compare the performance of running a foreach loop vs using the array_filter function in PHP. I wanted to compare the results time when running at large scales with multiple depths. No matter the depth, all tests were filtering out integer values less than six from an array set of 200 elements.

  • Functions tested: foreach & array_filter
  • array depths: 1, 2
  • total array elements: 200
  • Scenario: filter out integer values less than 6

Load Testing Findings & Notes

I’ll be honest. These findings really shocked me. I did not expect the foreach loop to win. But, it’s surprising by how much it won. The array_filter function was significantly slower than the foreach loop in this test scenario. These results aren’t conclusive as we need more real-world & complex filtering scenarios.. but it still shows the computational cost of filtering arrays in PHP.

  • foreach loop is significantly faster on simple filtering scenarios
  • array_filter code is slimmer, more readable and less error-prone
  • filtering arrays in PHP is expensive. Consider organizing array before getting to PHP execution code
  • Need more complex tests to declare foreach loop as more performant over array_filter

Array_Filter Code Example Used in Load Test

array filter built in function

/**
* array_filter function
* filter out values less than 6
* array depth: 1
$newArray = array_filter($baseArray, function ($val) {
        return $val > 5;
    });

/**
* array_filter function
* filter out 2nd level values less than 6
* array depth: 2
$newArray = array_filter($baseArray, function ($val) {
  

foreach Loop Array Filter Code Example

/**
* foreach loop
* filter out values less than 6
* array depth: 1
*/

$newArray = [];
    
foreach ($baseArray as $val) {
  if ($val > 5) {
    $newArray[] = $val;
  }
}

/**
* foreach loop
* filter out 2nd level values less than 6
* array depth: 2
*/
$newArray = [];
    
foreach ($baseArray as $val) {
  if ($val["number"] > 5) {
    $newArray[] = $val;
  }
}

What is the array_filter function in PHP

array_filter is the built in function to filter elements of an array. It is generally the preferred PHP array filter function. You pass an input array and a callback function. The final result array includes all elements where the callback function returns true.

The array_filter function passes each array element to the callback function. The function iterates over the current value of each array element. The resulting output array is a new instance that only includes the desired filtered array elements.

It has been around since PHP 5 and is the most efficient way to scope a large array.

There may be times that a loop will be preferable in some complex and corner cases but that’s not what’s happening here. We forget to give the PHP array_filter function the love it deserves for the more commonly used loops whenever we’re knee-deep in a deadline due two weeks ago.

But that’s not an excuse. Let’s see the details of this PHP array filter function.

Let’s break it down.

array_filter parameters

The array_filter function allows for 3 parameters. The array parameter that should be filtered, a callback function to filter the arrays, and a mode used to determine how you would want to filter. Only the first parameter is required.

  • $originalArray: (array) (required)The array that needs to be filtered
  • $callbackFunction: (function) (optional) The function filters the array. If null is passed, then it will just return an emptied array. This seems a little silly. You should use empty().
  • $mode: (int) (flag optional) Decide if you want to filter by value, key or both. The Defaults to value. Pass in a predefined constant mode

Modes available in the array_filter PHP callback function

3 modes are available in the array_filter function. They allow you to filter the arrays by value, key, or both key and value. The default mode is to filter by the value. The parameter expects an integer, but PHP provides additional constants to help remember the correct value.

The only argument in the callback function is the current array element.

  • ARRAY_FILTER_USE_KEY: 1 – Filters by Array Keys
  • ARRAY_FILTER_USE_BOTH: 2 – Filter arrays by both key & value

array_filter return value

The array_filter returns a new subset array of any array elements where the callback function returns true. It creates a new array instance that can be used for continuing code development.

Click here to see the official PHP documentation on array_filter

When you should use a foreach loop instead of the array_filter function

A foreach loop is better than the array_filter function whenever your script requires higher performance on single-level data sets. In my tests of arrays with 200 integer elements, I have found that it will shave 5 seconds from response time when called 1 million consecutive times.

These few saved seconds could have a major impact on an app requiring heavy computation. If you believe you may require 100k+ simultaneous requests on a single-level array then you will want to use the foreach loop instead of the array_filter function.

Pros:

  • More performant for single-level simple arrays
  • foreach loops are commonly used in many programming scenarios.

Cons:

  • Slower performance in complex filtering requirements.
  • More complex and longer code is prone to future bugs and developer confusion

Using array_filter in the real world.

Ok. let’s get out of the class and into the practical. I learn best by doing. The following content is real-world scenarios where we explain how to break down arrays in PHP efficiently.

These are code examples that you will come across often. Let’s make sure to do it the right way.

How to Filter PHP Associative Arrays

Associative arrays in PHP are multi-faceted in that you can treat them as lists or hashmaps with keys and values. Sounds rather complicated, but they are easy to understand and used commonly as a data structure. We can instead think about it in terms of operations that can be performed on it, which could be insertion, deletion, copying, filtering et cetera.

Nonetheless, we can use direct indexing or get values by using their keys. We are more interested to see how to filter arrays using PHP. There has already been a lot of related content on FuelingPHP

Needless to say that FuelingPHP offers an in-depth tutorial, “How to filter PHP associative array.

The article includes two main sections.

  1. How to filter PHP associative array by value
  2. How to filter PHP associative array by key.

Filter arrays by values using PHP

The article features three examples driven by a case study to filter students based on their semesters or courses. You can see the data and related examples in much more detail. The following are snippets of all three examples that have been used there.

The following example uses an iterative approach to filter students based on their semester. This approach is handy for lean list-like structures. However, as the nesting increases, or when we have arrays within arrays within arrays, this approach can be inefficient and slow.

function filterStudentsBySemester($data, $semester) {
   $filtered_arr = [];
   foreach($data as $k => $v) {
       if( $v["Semester"] > $semester ) {
           $filtered_arr[$k] = $v;
       }
   }
 
   return $filtered_arr;
}

To tackle this limitation, we can use the recursive approach which is more flexible and robust than iteration. The following example uses a recursive approach to list students’ information. Observe that in recursion a function can call itself repeatedly unless some terminating condition is met that breaks this call loop.

function listStudentsInfo($data)
{
   foreach($data as $k => $v)
   {
       if(gettype($v) == "array")
       {
        
           listStudentsInfo($v);
      
       }
 
       else if ($k == "Name") echo $v." has taken ";
 
       else if ($k == "Semester") echo "in semester#".$v."\n";
 
       else {
           echo $v.", ";
       }
   }
}

That’s not all. We also have an array_filter() example that uses a callback function to filter students who have passed the fifth semester. These inline-style higher-order functions are popular in front-end dev circles especially because they are lean and cleaner and sometimes integrate well with the presentational layer of an application.

$senior_students = array_filter($students_data, function($v) {
   return $v["Semester"] > 5;
});

Filter arrays by keys using PHP

After value filters, we also need to explore more about how to filter an array by keys. The article features a couple of examples for that: for each loop and array_filter(). Here are both of these codes in action.

//Filter associative array by key using a foreach loop
function getStudentsByMajor($data, $major)
{
   $filtered_arr = [];
   foreach($data as $k => $v) {
       if(substr($k, 0, 2) == $major) {
           $filtered_arr[$k] = $v;
       }
   }
 
   return $filtered_arr;
}

//Filter associative array by key using array_filter()
function getStudentsByMajor($data, $major)
{
   return array_filter($data, function($k) use ($major) {
       return substr($k, 0, 2) == $major;
   }, ARRAY_FILTER_USE_KEY);
}

The for each loop provides a reference to both key and value during an iteration with the syntax as shown. The later example with an array_filter() call uses the ARRAY_FILTER_USE_KEY flag to fetch keys instead.

Filter Arrays Using Doctrine ArrayCollection in PHP

Doctrine’s ArrayCollection is a nice wrapper over the native PHP arrays to give them Object Oriented Programming (OOP) capabilities and one of them is calling filter() on an instance of ArrayCollection.

<?php
require __DIR__ . '/vendor/autoload.php';
 
use Doctrine\Common\Collections\ArrayCollection;
 
$numbers = new ArrayCollection([-1000, -100, -10, 0, 10, 100, 1000]);
 
$mappedNumbers = $numbers->filter(function($num) {
    return $num > 0; //Keep the positive integers only.
}); //[0, 10, 100, 1000]
 
?>

Read more about it at FuelingPHP’s  “How to Use Doctrine ArrayCollection Map and Filter Functions.” 

Filter Array of Object in PHP

Arrays are not limited to primitive types only but they can house complex object types. Learn more about how to create, sort, & filter an array of objects in PHP. Meanwhile, here’s an example from the same article showing how to filter an object array using array_map().

// Functional requirements:
// We need to check a value inside our array of objects in PHP.
// Make a list of the values on the results with if it equaled expected value.

// Note: We are using the example array of Dog objects from our first example in PHP.
// Assume that we have already decoded and serialized our data into PHP.
// You can review above example if you need to decode or serialize.

// $dogsResult assumes to exist.


function checkResults(array $dogs, string $expectedProperty, string $expectedValue): array 
{
  $results = array_map(
    function($val) use ($expectedValue, $expectedProperty) {
      if (!isset($val->$expectedProperty)) {
        throw new Exception("Array doesn't contain expected property");
      }
      return [
        'isCorrect' => $val->$expectedProperty === $expectedValue,
        'value' => $val->expectedProperty
       ];
     },
    $dogs
  );

  return $results;
}

Filter Object Arrays by Values in PHP

Arrays of objects also have keys and value because they are associative at the end of the day regardless of the datatypes they can have. So, how to filter objects by keys out of an array? Learn more about it here.

Just to save you time and give you a quick glimpse, here are the snippets from the article itself.

//The array that will have the filtered results.
$filtered_arr = [];
 
// A foreach loop to iterate over key value pairs in the associative array.
foreach($employees_arr as $name=>$employee)
{
    //If the salary is more than 12,0000.
    if($employee->get_salary() > 12000)
    {
        //Push to filtered array
        array_push($filtered_arr,$employee);
    }
}


//Array_filter to filter employee whose salaries are more than 12,000.
$filtered_arr = array_filter(
  $employees_arr,function($employee){ 
    return $employee->get_salary() > 12000;
  }
);

Sounds repetitive but that’s the most generic solution out there. You can factor in implementation details but iterables are meant to be iterated and thus we use a for each loop and array_filter() here as well.

Filter Object Arrays by Keys in PHP

“How to filter arrays of objects by keys in PHP” is yet another article on a similar topic using very similar solutions: for each loop with key reference and array_filter() with the right flag  ARRAY_FILTER_USE_KEY.

//Array_filter to filter employee by key values. The key values are the employee names.
$filtered_arr = array_filter($employees_arr,function($key){ return $key == "Karen";},ARRAY_FILTER_USE_KEY);

Filter PHP Multidimensional Array 

Say Multidimensional! Arrays in arrays in arrays…. 

Sounds complicated.

But we have recursion to the rescue which is as we have seen more robust and less tightly coupled with the number of nesting arrays may have. Here’s a classic recursion example from the “Filter Multidimensional Array by Value in PHP

function recurse_arr($arr,&$filtered_arr, $exp) {
foreach($arr as $key=>$value) {    
    if(isset($value["Experience(years)"])) {
        if($value["Experience(years)"] > $exp) {
            $filtered_arr[$key] = $value;
        }  
    }
   
    //If there's an array within array then recall the function.
    elseif(gettype($value) == 'array') {
        recurse_arr($value,$filtered_arr);
    }
 
}
 
return $filtered_arr;
}

You can also use callbacks with this recursive function to implement more flexibly. You can pass in an array using a callback function. This recursive function takes 3 arguments.

Nevertheless, recursion generally has a function calling itself repeatedly unless it hits a stopping condition, and not having one means a “StackOverFlow Error”.

Filtering Arrays in PHP with array_filter

Thus far, we have seen an organizational article on the bulk of quality content on filtering arrays. Though there is no silver bullet to all problems, we can identify use cases where one solution can be better than its alternatives.

We have included sections and their relevant articles so you can zoom in on any of those when you want to. We have an elaborative guide of associative arrays followed by more informational guides on object arrays and multi-dimensional. As a generic rule, think of recursion when dealing with nested and repeating structures and sub-structures, you will thank us later.

Not to forget about Doctrine ArrayCollection, a nice OOP library for PHP that features many methods that are usually expected for an array. Hopefully, many of these tutorials and examples will get you going. Until next time!

Hope you’ve enjoyed this article, Stay tuned at FuelingPHP.

Get Deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.