How to filter array of objects by key in PHP

Summary:

Use the array_filter function to filter an array by key in php. Pass in an array and a function as params. Return true on the passed function whenever the key matches your criteria.

Code Snippet: preferred method to filter array of objects by key

The following code snippet is a quick way to filter array of objects by key 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.

<?php 

// 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($key){ 
      return $key === 0;
   },
   ARRAY_FILTER_USE_KEY);
 
//Gets the filtered array.
print_r($filtered_arr);
 
 
/*
OUTPUT
Array
(
    [0] => stdClass   
        ( 
            [name] => charles
            [type] => cat
        )
)
*/

Setup: objects & classes to filter array of objects in PHP

Disclaimer

If you’re familiar with fundamental concepts of classes and objects in PHP, you can skip to options directly.

Introduction

PHP arrays are versatile in terms of the data types they could hold. Hence, an array can have mixed data types. PHP associative arrays are in the form of key and value pairs. It is often desirable to filter these arrays based on either the key or value. That’s why in this article, we’ll learn how to filter array of objects by key in PHP.

Filtering an array gets important as your application becomes more data-driven. Here we’ll see an array of objects. Although the techniques here work with any array, we want to touch upon PHP classes and objects.

filter array of objects by key in PHP

PHP Classes and Objects

 filter array of objects by key in PHP

Classes and objects are central ideas of Object Oriented Programming. PHP supports classes and objects. We’ll understand what they are using an analogy.

Consider a master plan for a home. A master plan includes an architectural map that outlines the attributes and structure of a home. Based on a single master plan, a constructor could build maybe hundreds of homes. Not surprisingly, all these homes would have the same attributes and structure because the same master plan inspires them all.

Class

A class is a template for objects. So, a class is just like an outline that defines attributes and methods. You can declare a class by using the class keyword followed by class name and parenthesis. Objects are created based on a class, and hence they are called instances of a class.

Here’s an example of an employee class that defines attributes and methods. We will discuss the components of a class in more detail someday.

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;
    }
 
 
}

Object

An object is an instance of a class. Objects are created based on a class, and that’s why the objects of the same class have the same set of attributes and functions. Objects are instantiated from a class using the new keyword. Here’s an example of employee objects created from the employee class defined already.

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

Each of these objects has three attributes as defined in their class. These attributes are id, name, and salary. Let’s put these objects into an array and use that in the following examples.

$employees_arr = array(
    $employee_1->get_name() => $employee_1,
    $employee_2->get_name() => $employee_2,
    $employee_3->get_name() => $employee_3,
    $employee_4->get_name() => $employee_4,
    $employee_5->get_name() => $employee_5,
);

Solutions: Filtering array of objects by key

Option 1: Filter array of objects by key in PHP using a foreach loop

You’ll be quite familiar with the foreach loop if you’re a regular reader of our articles because we’ve been using the foreach loop almost every time there’s a need to work with arrays in PHP. Here we’ll be using the same employee objects array and iterate over it through a foreach loop.

We’ll filter out an employee named “Anna.” This operation is much like querying a database for a record.

//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 there's a name Anna
    if($name == "Anna")
    {
        //Push to filtered array
        array_push($filtered_arr,$employee);
    }
}
 
print_r($filtered_arr);
 
/*
OUTPUT
Array
(
    [0] => Employee Object   
        (
            [id] => 2        
            [name] => Anna   
            [salary] => 14000
        )
 
)
*/

So, we have compared the key with string "Anna" and pushed the right object to the filtered array. This approach is pretty straightforward. Let’s see a more sophisticated approach to do the same thing.

Option 2: Filter array of objects by key in PHP using array_filter

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 one 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’ve been using the same array of employee objects that we’ve seen in the introduction. Here we are using the array_filter function to filter the array of objects by key in PHP.

//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);
 
//Gets the filtered array.
print_r($filtered_arr);
 
/*
OUTPUT
Array
(
    [Karen] => Employee Object
        (
            [id] => 5
            [name] => Karen   
            [salary] => 11000 
        )
 
)
*/

A clever one-liner does an equivalent of a foreach loop. Pay close attention to the $mode, ARRAY_FILTER_USE_KEY. The $mode passes key values to the callback function as the array_filter loops through the array behind the scenes.

You can implement callback functions based on your logic. The callback function in this example includes a statement that compares the key to “Karen” and filters out that employee. In summary, array_filter is the most followed approach for filtering an array.

Conclusion

We’ve seen what classes and objects are in PHP. Based on the array of objects, we have explored two options to filter the array of objects by key in PHP. The first option uses a foreach loop, while the other option uses the function. In a future article, we’ll see how to filter an array of objects by value in PHP. So, stay tuned for more interesting and exciting content related to PHP.

Want to explore more useful PHP tutorials?

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

Difference between while and do-while loops in PHP

When to use while vs foreach loops in PHP

How to put values in an associative array into another array in PHP


© 2022 Confident.Systems