Filter Array of Objects by Value: 5 PHP Code Examples in 2023

Last Updated on

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

How to Filter PHP arrays

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 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 returned truthy (not null or false) will get pushed into the new filtered array.

Check out the example below to quickly filter an array in PHP by value.

PHP array_filter Code Example


// 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);

How to Filter an array of objects by value

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.

Filter Array of Objects by Value PHP Code Example



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

Steps to Filter array of objects using PHP

  1. Convert JSON into PHP Array with json_decode
  2. Filter the PHP array using the array_filter function
  3. Continue processing code

Optional Methods to Filtering Arrays in PHP

MethodDescription
array_filter()Filters the elements of an array using a callback function and returns the filtered array. The callback function receives each element of the array as an argument and should return true to include the element in the filtered array, or false to exclude it.
foreach loopLoops through each element of an array and applies a conditional statement to filter the elements. The conditional statement is typically an if statement that checks whether the current element meets a certain condition. The filtered elements can be added to a new array using array_push(), or the original array can be modified in place.

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:

What are Objects & Classes in PHP

Disclaimer

  • If you’re unfamiliar with the class and objects, check out a detailed explanation in this article.
  • If you know 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. We’ve repeatedly mentioned keys and values and how associative arrays keep key and value pairs.

Looping over an array’s values and filtering out some of them is not uncommon.

filter array of objects by value in PHP

The options 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.

Options to Filter Array of Objects by Value Using PHP

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 a PHP code 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.

PHP array_filter Code 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

Filtering PHP Arrays of Objects by Value

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.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.