Filter Array of Objects by Key: 5 PHP Code Examples (2023)

Last Updated on

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

Filter Array of Objects PHP Code Example

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.


// 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(
      return $key === 0;
//Gets the filtered array.
    [0] => stdClass   
            [name] => charles
            [type] => cat

Using objects & classes to filter array of objects in PHP


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


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.

Click here to read our intro to PHP Object-Oriented Programming Article

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.


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 using the class keyword followed by the class name and parenthesis. Objects are created based on a class, hence 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.

We’ve also written an excellent intro to PHP Classes article. Click here to check it out.

PHP Class Code Examples

class Employee
    public $id;
    public $name;
    public $salary;
    function __construct($id,$name,$salary)
        $this->id = $id;
        $this->name = $name;
        $this->salary = $salary;
    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;


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.

PHP Objects Code Examples

$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,

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 as we’ve used them extensively.

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.

Foreach Loop PHP Filter 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 there's a name Anna
    if($name == "Anna")
        //Push to filtered array
    [0] => Employee Object   
            [id] => 2        
            [name] => Anna   
            [salary] => 14000

So, we compared the key with the 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.

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.


Filters array elements using a callback function

Function Signature

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


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


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.

Filter Objects by Key Code 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.
    [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.

Filtering Array of Objects by Key

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

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.