Skip to content
Home » How to Filter Arrays in PHP with array_filter() Code Examples

How to Filter Arrays in PHP with array_filter() Code Examples

How to use the array_filter PHP 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 that we have listed below and dig a little 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 what the results time would be when running at large scales with multiple depths. All tests no matter the depth were filtering out integer values less than 6 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 Used in Load Test

array_filter functions

/**
* 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

/**
* 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

The PHP array_filter function is the core method to reduce and return a subset array of desired values from a larger array. It has been around since PHP 5 and is the most efficient way to scope a large array.

This is an older function but it’s sadly not used to its potential. You will still find many dev projects where the developer used a foreach to filter an array.

What’s up with that?

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 just forget to give the array_filter the love it deserves for the more commonly used loops whenever we’re knee-deep in a deadline that was due 2 weeks ago.

But that’s not an excuse. Write the right code man! array_filter is our friend.

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 used to filter the array. If null is passed, then it will just return an emptied array. This seems a little silly. You should just use empty().
  • $mode: (int) (optional) Decide if you want to filter by value, key or both. Defaults to value. Pass in a predefined constant

Modes available in the array_filter PHP function

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

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

array_filter return value

The array_filter returns a new subset array of the values that you have filtered using your callback function. 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 a better choice than the array_filter function whenever your script requires higher performance on single-level data sets. I have found in my tests of arrays with 200 integer elements that it will shave 5 seconds from response time when called 1 million consecutive times.

These few seconds saved could have a major impact on an app that requires heavy computation requirements. If you believe you may have a requirement of 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 break down how to efficiently break down arrays in PHP.

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 Multi-dimensional PHP Arrays 

Say multi-dimensional! 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 have a more flexible implementation. 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

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

We have included sections and their relevant articles for your ease 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 which is a nice OOP library for PHP and features many methods that usually are 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.