Filter Multidimensional Array by Value with PHP Code Examples

Last Updated on

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

Filter PHP multidimensional arrays code examples

PHP multidimensional array can hold any number of nested arrays. Sometimes we just want a subset of the values of an array, and for that reason, we need to figure out how PHP filter nested array. In this article, we’ll see how to filter PHP multidimensional array.

$filtered_arr = [];
foreach($developers as $tech=>$developer) {
    array_push($filtered_arr,array_filter($developer,function($v,$k){
        if($v["Experience(years)"] > 2) {
            return $v;
        }
    },ARRAY_FILTER_USE_BOTH));
}
 
print_r(array_merge(...$filtered_arr));
filter php multidimensional array

We will explore three options to filter PHP multidimensional array by value. The first approach is iterative, the second recursive, and the third approach uses PHP array_filter function. So, let’s jump to the article without any further ado.

Have you tried any of the following highly relevant Pluralsight PHP Courses?

We love Pluralsight because it has thousands of high-quality course content and is extremely affordable. You don’t have to pay for individual courses. It’s a really small monthly membership and you get access to the entire catalog. You can track and review all of your progress and also obtain additional certifications.

Courses

  • PHP Design Patterns
  • PHP: The Big Picture
  • PHP 8: Web Application Security
  • High-Performance PHP
  • Object-Oriented PHP

Learning Paths:

  • PHP Development Fundamentals

Pluralsight Free Trial

Curious about Pluralsight but not ready to commit? We understand. We were able to get a free trial for you to test-drive and see all of their courses. Click on the link below

Try a Pluralsight free trial for 7 days!

Developers Array

In the upcoming examples, we will be using an array that holds information about developers at a company. We call this array “developers.” This array is multidimensional and looks like this. So, make sure you check out the array structure and familiarize yourself before we jump into examples.

$developers = [
    "PHP" => [
        "Nancy" => ["Experience(years)"=>3,"Skills"=>["Laravel","GIT","HTML","CSS"]],
        "Josh" => ["Experience(years)"=>2,"Skills"=>["MVC","GIT","Docker","Bootstrap","CSS"]],
    ],
    "Java"=>[
        "Bruce" => ["Experience(years)"=>5,"Skills"=>["Java Spring","Docker","GIT","Flutter"]],
        "Karen" => ["Experience(years)"=>2,"Skills"=>["Java Spring","GIT","Android"]],
    ],
    "Javascript"=>[
        "Adam" => ["Experience(years)"=>3,"Skills"=>["React","HTML","CSS","React Native"]],
        "Micheal" => ["Experience(years)"=>5,"Skills"=>["React","Node","Express","React Native"]],
    ],
    "Python"=>[
        "Ajay" => ["Experience(years)"=>4,"Skills"=>["TensorFlow","Pytorch","Pandas"]],
    ],
    "C++"=>[
        "Allan" => ["Experience(years)"=>5,"Skills"=>["RasberryPI"]],
    ]
];

#1 – Filter PHP multidimensional array using an iterative approach

The iterative approach uses loops to access and iterate over an iterable data structure like an array. However, as the loop nesting increases, the performance worsens. Moreover, we need to know the number of sublevels or subarrays to decide on the number of nested loops we will be using.

filter php multidimensional array

Let’s use an iterative approach for the query given as follows:

“Filter Employees with more than two years of experience”

Example

//This array will hold the filtered response
$filtered_arr = [];
 
//Iterates over the tech like PHP, Java, ...
foreach($developers as $tech=>$developer) {
    //Iterates over the developer records...
    foreach($developer as $name=>$details) {
        if($details["Experience(years)"] > 2) {
            $filtered_arr[$name] = $details;
        }
    }
}
 
print_r($filtered_arr);

Output

/*
OUTPUT
Array
(
    [Nancy] => Array
        (
            [Experience(years)] => 3
            [Skills] => Array      
                (
                    [0] => Laravel  
                    [1] => GIT      
                    [2] => HTML    
                    [3] => CSS      
                )
 
        )
 
    [Bruce] => Array
        (
            [Experience(years)] => 5
            [Skills] => Array
                (
                    [0] => Java Spring
                    [1] => Docker
                    [2] => GIT
                    [3] => Flutter
                )
 
        )
 
    [Adam] => Array
        (
            [Experience(years)] => 3
            [Skills] => Array
                (
                    [0] => React
                    [1] => HTML
                    [2] => CSS
                    [3] => React Native
                )
 
        )
 
    [Micheal] => Array
        (
            [Experience(years)] => 5
            [Skills] => Array
                (
                    [0] => React
                    [1] => Node
                    [2] => Express
                    [3] => React Native
                )
 
        )
 
    [Ajay] => Array
        (
            [Experience(years)] => 4
            [Skills] => Array
                (
                    [0] => TensorFlow
                    [1] => Pytorch
                    [2] => Pandas
                )
 
        )
 
    [Allan] => Array
        (
            [Experience(years)] => 5
            [Skills] => Array
                (
                    [0] => RasberryPI
                )
 
        )
 
)
*/

Voila! The filtered array includes all the employees with more than two years of experience. Observe that we have used nested loops. The nesting may increase if we have more nested arrays, and that’s a drawback of the iterative approach. Luckily have an alternative approach called recursion and that we are going to see next.

#2 – Filter PHP multidimensional array using a recursive approach

The recursive approach relies on repeated function calls to break a fairly complex task into smaller bits. So, it takes each chunk of the array and repeats the same iteration logic. Therefore we don’t have to worry about nested loops because recursion takes care of that. We will see that in the following example for the same query done previously.

Example

function recurse_arr($arr,&$filtered_arr) {
foreach($arr as $key=>$value) {    
    if(isset($value["Experience(years)"])) {
        if($value["Experience(years)"] > 2) {
            $filtered_arr[$key] = $value;
        }  
    }
   
    //If there's an array within array then recall the function.
    elseif(gettype($value) == 'array') {
        recurse_arr($value,$filtered_arr);
    }
 
}
 
return $filtered_arr;
}
 
$filtered_arr = [];
print_r(recurse_arr($developers,$filtered_arr));

The output is similar to what we have seen before in the case of iterative. Notice that we have defined a single loop, and the recursion logic is good to go with that because no matter how many subarrays we have, the recursion code redoes the loop logic for every subarray.

Lastly, let’s see the third option that uses the array_filter function.

#3 – Filter PHP multidimensional array using array_filter function

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

Here’s how PHP filter nested array using array_filter function.

$filtered_arr = [];
foreach($developers as $tech=>$developer) {
    array_push($filtered_arr,array_filter($developer,function($v,$k){
        if($v["Experience(years)"] > 2) {
            return $v;
        }
    },ARRAY_FILTER_USE_BOTH));
}
 
print_r(array_merge(...$filtered_arr));

The output is the same as we have seen in the iterative approach. 

Conclusion

We have seen how to filter PHP multidimensional array by value using three different options. The iterative and recursive approaches followed by PHP array_filter to filter PHP multidimensional array. We hope you’ve learned something new today. Stay tuned for more exciting articles related to 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.