How to Filter PHP Associative Arrays with 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 Associative Array Code Example

You will want to use the array_filter function on a PHP associative array to filter correctly. Many times, your array may also be multi-dimensional. We recommend creating a unique array filter function using a recursive pattern.

Here’s a sample code snippet from the article.

// Option 1: Using a array_filter function

function filterStudentsBySemesterOne($students_data) {
  return array_filter($students_data, function($v) {
   return $v["Semester"] > 5;
  });
}

// Option 2: Filter associative arrays using an iterative approach (not recommended)

function filterStudentsBySemester($data, $semester) {
  // Do some logic to determine whether we can return true.
   $filtered_arr = [];
   foreach($data as $k => $v) {
       if( $v["Semester"] > $semester ) {
           $filtered_arr[$k] = $v;
       }
   }
 
   return $filtered_arr;
}

This code is an example of an iterative approach. There are other options as well. Check out the article to see more.

Relevant Content – PHP Associative Arrays

PHP associative arrays are similar to hash maps. They store a key-value pair. A key has to be unique and has an associated value. Arrays in PHP come with many useful core functions. These functions come in handy one way or the other when trying to transform and manipulate arrays.

One frequent operation could be filtering an array based on a key or a value. However, this subject is not as simple as it sounds because arrays are not always linear and may involve multi-dimensions. This article explores that in detail. A relevant article about multidimensional arrays and recursive algorithms is also a good read.

Scenario: Filtering Associative Arrays with Students Data

Background & Setup: Students Associative Array in PHP

Let’s peek into the associative array that saves data about students. It is a three-dimensional associative array.

$students_data = [
   "CS01" => [
       "Name" => "Alex",
       "Courses" => ["Programming", "Datastructure & Algorithms", "System Design"],
       "Semester" => 3
   ],
   "EE01" => [
       "Name" => "Jennifer",
       "Courses" => ["Electrical Circuits", "Electricity & Magnetism", "Signal Processing"],
       "Semester" => 7
   ],
   "CS02" => [
       "Name" => "Dany",
       "Courses" => ["Advanced Programming", "Image Processing", "Machine Learning"],
       "Semester" => 6
   ],
   "EE02" => [
       "Name" => "Sam",
       "Courses" => ["Calculus-II", "Signal Processing", "Circuit Design"],
       "Semester" => 8
   ],
   "C203" => [
       "Name" => "Linda",
       "Courses" => ["Programming", "Algorithmic Analysis", "Object Oriented Programming"],
       "Semester" => 5
   ]
];

The key value combines a major subject code and a student’s ID. For instance, “CS” is for “Computer Science”, and “EE” is for “Electrical Engineering”.

The value is an array that includes more data about a student, including a subarray of courses to be included in the semester. 

So, that’s a sample array of data we’ll use in the following examples. Let’s begin with examples of how to filter PHP associative array by key and value.

PHP Filter Associative Array by Value

Associative arrays can span more than one dimension. The options below include two main approaches.

  • Iterative Approach.
  • Recursive Approach.

We’ll also see which one is more robust for multidimensional arrays in PHP.  

Option1 – Filter Associative Array PHP by Value Using Iterative Approach

The iterative approach involves looping through elements of an array. This approach is simple, but it can quickly get messy and inefficient with increasing dimensions of an array. For instance, we will need three nested loops to loop through a three-dimensional array.

The downside is that the time complexity increases with nesting, and the runtime can increase many folds with more dimensions and increasing array size.

Query#1 – All Senior Students (Starting from Semester 6) 

Let’s filter the associative array by value. The filter value will be the “Semester”. The example returns all the students enrolled in Semester 6 and beyond.

function filterStudentsBySemester($data, $semester) {
   $filtered_arr = [];
   foreach($data as $k => $v) {
       if( $v["Semester"] > $semester ) {
           $filtered_arr[$k] = $v;
       }
   }
 
   return $filtered_arr;
}

Here’s an example using an iterative approach. We have a loop to traverse through the array and filter students based on the semester data. The filter clause is quite a primitive boolean expression.

Let’s call this function now…

$senior_students = filterStudentsBySemester($students_data, 5);

And here’s the output…

Array
(
    [EE01] => Array
        (
            [Name] => Jennifer
            [Courses] => Array
                (
                    [0] => Electrical Circuits
                    [1] => Electricity & Magnetism
                    [2] => Signal Processing
                )

            [Semester] => 7
        )

    [CS02] => Array
        (
            [Name] => Dany
            [Courses] => Array
                (
                    [0] => Advanced Programming
                    [1] => Image Processing
                    [2] => Machine Learning
                )

            [Semester] => 6
        )

    [EE02] => Array
        (
            [Name] => Sam
            [Courses] => Array
                (
                    [0] => Calculus-II
                    [1] => Signal Processing
                    [2] => Circuit Design
                )

            [Semester] => 8
        )

)

Query#2 – All Students Studying Programming

Let’s see another query that filters the associative array and returns all the students who have taken the “Programming” course this semester.

function filterStudentsByCourse($data, $course)
{
   $filtered_arr = [];
   foreach($data as $k => $v) {
       foreach($v["Courses"] as $c) {
           if(strtolower($c) == strtolower($course)){
               $filtered_arr[$k] = $v;
           }
       }
   }
 
   return $filtered_arr;
}

The function uses a nested foreach loop to iterate over the “Courses” subarray. As mentioned, the iterative approach can get ugly in terms of complexity as the array adds dimensions. 

Another downside is that the iterative approach is not a generalized solution. You need to know the array dimensions before implementing an iterative solution. 

Anyways, we will see a more generalized solution up next. For now, let’s call this function.

$students_by_course = filterStudentsByCourse($students_data, "Programming");

Here’s the output.

Array
(
    [CS01] => Array
        (
            [Name] => Alex
            [Courses] => Array
                (
                    [0] => Programming
                    [1] => Datastructure & Algorithms
                    [2] => System Design
                )

            [Semester] => 3
        )

    [C203] => Array
        (
            [Name] => Linda
            [Courses] => Array
                (
                    [0] => Programming
                    [1] => Algorithmic Analysis
                    [2] => Object Oriented Programming
                )

            [Semester] => 5
        )

)

Voila! Now is the time to move on to learn how to filter PHP associate array using a recursive approach.

Option2 – Filter Associative Array PHP by Value Using Recursive Approach

The recursion approach breaks down a complex task into subtasks. Consequently, it recalls a function to sort out the chunks of a big problem. It gives you a generalized and effective solution. Let’s implement a query logic to learn more about the efficacy of this solution.

how to filter php associative array

Query#3 – Print Students Information

Let’s implement a function that lists students’ information. We need to format the information as follows:

“A has taken B, C, D, in semester#X”

Recall that an iterative approach will use a nested loop to iterate over the courses of subarrays. 

The following example is how recursion goes about this problem.

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.", ";
       }
   }
}

The example may seem hard-coded enough, but here’s the catch, if we can increase the dimensions of the “Courses” subarray, this function won’t break. That’s because this recursive algorithm will always reach the deepest nodes.

Here’s the output.

Alex has taken Programming, Datastructure & Algorithms, System Design, in semester#3
Jennifer has taken Electrical Circuits, Electricity & Magnetism, Signal Processing, in semester#7
Dany has taken Advanced Programming, Image Processing, Machine Learning, in semester#6
Sam has taken Calculus-II, Signal Processing, Circuit Design, in semester#8
Linda has taken Programming, Algorithmic Analysis, Object Oriented Programming, in semester#5

Now, what happens in the iterative approach? Guess what – you need to add another nested loop for the extra dimension. So the iterative algorithm doesn’t generalize.

That’s just one example of the recursive algorithm. We have an entire article on multidimensional arrays and recursive algorithms.

Option3 – Filter Associative Array PHP by Value Using array_filter Function

The array_filter function expects an array and a callback function. The function provides a nice and compact way to filter an array in PHP. You can also use this function in the front-end to embed it nicely with the visual elements of a web page.

Let’s redo query#1 and filter senior students.

$senior_students = array_filter($students_data, function($v) {
   return $v["Semester"] > 5;
});

Comparing it to the last example in query#1, this code is much more clean and compact.

That covers PHP filter associative array by value. Let’s move to the next section which filters by associative array by key.

PHP Filter Associative Array by Key

Associative arrays have a unique key and an associated value. This section explains how to filter PHP associative array by key. So, let’s jump to the first example without any further ado.

Option1 – Filter Associative Array PHP by Key Using foreach 

Let’s filter the students’ data by key and filter all the EE students. As a result, we get students who are studying CS. Let’s use the foreach loop to iterate over the keys and their values.

function getStudentsByMajor($data, $major)
{
   $filtered_arr = [];
   foreach($data as $k => $v) {
       if(substr($k, 0, 2) == $major) {
           $filtered_arr[$k] = $v;
       }
   }
 
   return $filtered_arr;
}

The $k and $v in the foreach loop refer to key and value respectively. Let’s call this function.

$CS_students = getStudentsByMajor($students_data, "CS");

Here’s the output.

Array
(
    [CS01] => Array
        (
            [Name] => Alex
            [Courses] => Array
                (
                    [0] => Programming
                    [1] => Datastructure & Algorithms
                    [2] => System Design
                )

            [Semester] => 3
        )

    [CS02] => Array
        (
            [Name] => Dany
            [Courses] => Array
                (
                    [0] => Advanced Programming
                    [1] => Image Processing
                    [2] => Machine Learning
                )

            [Semester] => 6
        )

)

Option2 – Filter Associative Array PHP by Key Using array_filter

Remember array_filter PHP, a nice higher-order function that expects a callback for filter logic. We need to pass in a key to pass it the keys instead of values. 

Let’s redo the last example using array_filter in PHP.

function getStudentsByMajor($data, $major)
{
   return array_filter($data, function($k) use ($major) {
       return substr($k, 0, 2) == $major;
   }, ARRAY_FILTER_USE_KEY);
}

Observe the last argument ARRAY_FILTER_USE_KEY in the array_filter function, it passes keys to the callback function. The rest of the logic remains the same.

Phew! That was a lot of ground to cover. Let’s wrap this article up!

Conclusion – How to Filter PHP Associative Array

Wrap Up

This article explains how to filter PHP associative array. This article divides into two subsections. The first section deals with filtering associative arrays by values. This section explores three options further. The second section deals with filtering associative arrays by keys. This section breaks down into two further sections.

Classes and Functions Mentioned

gettype:  (PHP 4, 5, 7, 8)  A built-in PHP function available from PHP 4. It is stable, and given the utility, it doesn’t seem to depreciate in coming versions.

strtolower: (PHP 4, 5, 7, 8) This core PHP function is available from PHP4 and has been included in the latest version. Given its utility and stability, it seems to stay in the long run and remain stable throughout.

array_filter: (PHP 4.0.6, 5, 7, 8) This is a higher-order function that comes built-in right from version 4.0.6. Filter, map and reduce functions are popular in functional programming. It is popular and stable and could remain stable in the long run.

Want to learn more about PHP?

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

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.