How to filter an array of objects by value in PHP

Summary:

Use the array_filter function to filter an array by value in php. Pass in an array and a function as params. Return true on the passed function whenever the value matches your criteria. array_filter($myArray, function ($arrayItem) { return $arrayItem === $whateverCriteria });

Prereq: Filter PHP arrays by value with the array_filter function

Before we get to the more complicated scenario of filtering arrays of objects by value. Let’s show how to do a PHP array filter by value in general. This is pretty simple to do using the array_filter function. You pass in the original array as the first parameter and then a function as the second parameter. The array_filter function uses the passed function on each element in the array to determine whether it should get returned. Anything that is returned truthy (not null or false) will get pushed into the new filtered array. Check out the example below to do a quick filter of an array in PHP by value.


// Let's setup a scenario where we need to filter an array by values with cows.
$sampleArray = [0 => "horse", 1 => "cow", 2 => "pig", 3 => "cow"];

$filteredArray = array_filter(
    $sampleArray, 
    function($val){ 
      return $val === 'cow';
   });

// Let's var_dump the $filteredArray.
// You will see the results where you've filtered the array by value.
var_dump($filteredArray);

Final Code Snippet: Filter array of objects by value with the array_filter function

The following code snippet is a quick way to filter array of objects by value using the array_filter function. We recommend using the method for most array filtering use cases. Feel free to use this snippet and then follow along for more explanation.



// Dummy data just to populate function.
// I'm creating a json string as its an efficient way to create an array of objects.
// You can ignore this part and replace $objectsArray with your array.
$content = '[{"type": "cat", "name": "charles"}, {"type": "dog", "name": "sam"}, {"type": "donkey", "name": "frank"}]';

$objectsArray = json_decode($content);

//Array_filter to filter objects with cat as type
// This is where the work is done.
$filtered_arr = array_filter(
   $objectsArray,
   function($obj){ 
      return $obj->type === 'cat';
   });
 
//Gets the filtered array.
print_r($filtered_arr);
 
 
/*
OUTPUT
Array
(
    [0] => stdClass   
        ( 
            [name] => charles
            [type] => cat
        )
)
*/

Dig Deeper: filtering PHP arrays with the array_filter function

Still looking to get geeky with filtering PHP arrays? Of course you are. Check out some of our other high-value articles on the subject:

Setup: Objects & Classes for filtering the array object by value

Disclaimer

  • If you’re not familiar with what class and objects are, check out a detailed explanation in this article.
  • If you’re aware of class and object syntax in PHP, you can navigate to options directly. 

Introduction

In our previous article, we have seen how to filter an array of objects by key in PHP. Here we will see the next important part of how to filter array of objects by value in PHP. As we’ve repeatedly mentioned about keys and values and how associative arrays keep key and value pairs. It is not uncommon to loop over an array’s values and filter out some of them.

filter array of objects by value in PHP

The options that we’ll see work equally well for arrays of all types. However, we intend to use objects to touch upon some fundamental OOP concepts in PHP. So, before we begin, here’s a recap of what classes and objects look like in PHP.
We’ve seen classes and objects in much depth in a previous article.

PHP Class

filter array of objects by value in PHP

A class is a blueprint for objects. PHP class begins with the class keyword followed by the class name. The parenthesis encloses the attributes, constructors, and methods of the class. Here’s the example that we’ll be using throughout the article.

class Employee
{
     //Attributes
    public $id;
    public $name;
    public $salary;
 
 
    //Constructor
    function __construct($id,$name,$salary)
    {
        $this->id = $id;
        $this->name = $name;
        $this->salary = $salary;
    }
 
    //Methods 
    function get_id()
    {
        return $this->id;
    }
 
    function get_name()
    {
        return $this->name;
    }
 
    function get_salary()
    {
        return $this->salary;
    }
 
    function set_id($id)
    {
        $this->id = $id;
    }
 
    function set_name($name)
    {
        $this->name = $name;
    }
 
    function set_salary($salary)
    {
        $this->salary = $salary;
    }
 
 
}

The class here represents an Employee entity with attributes (Id, Name, Salary), a constructor function, and methods, mainly getters, and setters. The objects of the Employee class will have similar attributes, and each of these objects will represent an employee. We will see that next.

PHP Objects

Objects are instances of a class, and objects of the same class have similar attributes and properties. Here are a few instances of the Employee class.

$employee_1 = new Employee('1',"Rachel",15000);
$employee_2 = new Employee('2',"Anna",14000);
$employee_3 = new Employee('3',"Robert",13000);
$employee_4 = new Employee('4',"Micheal",12000);
$employee_5 = new Employee('5',"Karen",11000);

After the quick recap, let’s see what options are available to filter array of objects by value in PHP.

Solutions: Filtering array of objects by value

Option 1: foreach loop to Filter array of objects by value

We’ve been using a foreach loop to iterate over arrays. In the example, we will use a foreach loop to iterate over the values and filter those employees whose salaries are more than 12,000. Here’s the example.

//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);
    }
}
 
print_r($filtered_arr);
 
 
/*
OUTPUT
Array
(
    [0] => Employee Object   
        (
            [id] => 1        
            [name] => Rachel 
            [salary] => 15000
        )
 
    [1] => Employee Object   
        (
            [id] => 2        
            [name] => Anna   
            [salary] => 14000
        )
 
    [2] => Employee Object
        (
            [id] => 3
            [name] => Robert
            [salary] => 13000
        )
 
)
*/

Wonderful. We have filtered employees whose salaries are more than 12,000 USD. The foreach loop gives us a lot of edge with the pointers that get the key and value on each iteration. The logic to filter depends on the problem at hand, but the code pretty much remains the same. 

Next, we’ll see the array_filter function in PHP. It takes a callback function and filters an array based on the logic in the callback function.

Option 2: array_filter function to filter array of objects by value

The array_filter is a popular function that helps filter out an array based on the return value of a callback function. We’ve already seen array_filter in action in many of the articles. Here’s a recap of the function before we see an example.

Description

Filters array elements using a callback function

Function Signature

array_filter(array $array, ?callable $callback = null, int $mode = 0): array

Arguments

  • $array – The array to filter
  • $callback – A user-defined function
  • $mode –  Flag that determines the callback function’s parameter

Note

The $mode accepts the following flag values. 

  • ARRAY_FILTER_USE_KEY – pass key as the only argument to callback instead of the value
  • ARRAY_FILTER_USE_BOTH – pass both value and key as arguments to callback instead of the value

By default, the function passes only the key values to the callback function.

Return Type

The function returns a filtered array.

Example

We will redo the same example as we did with the foreach loop. However, we will be using the array_filter function here.

//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;
  }
);
 
//Gets the filtered array.
print_r($filtered_arr);
 
 
/*
OUTPUT
Array
(
    [0] => Employee Object   
        (
            [id] => 1        
            [name] => Rachel 
            [salary] => 15000
        )
 
    [1] => Employee Object   
        (
            [id] => 2        
            [name] => Anna   
            [salary] => 14000
        )
 
    [2] => Employee Object
        (
            [id] => 3
            [name] => Robert
            [salary] => 13000
        )
 
)
*/

Comparing the two options, this option is more concise as the actual code becomes clean and shorter. You can also declare a function outside and pass it to the array_filter

Conclusion

We’ve seen a recap of class and object syntax in PHP and explored two options to filter array of objects by value in PHP. The first option uses a foreach loop, while the second option makes use of the array_filter function. The latter option makes the code clean and shorter and focuses on the logic by taking a callback function as an argument.

Want to explore more useful PHP tutorials?

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

How to filter array of objects by key in PHP

Difference between while and do-while loops in PHP

When to use while vs foreach loops in PHP


© 2022 Confident.Systems