How to count values in multidimensional array PHP

Summary:

There are 3 different ways you can count the values in a multidimensional array. You can use an iterative, or recursive strategy or use several built-in functions. You should avoid the iterative if you have a large array.

Introduction

This article is about how to count values in multidimensional array PHP. In other ways, find the frequency of recurring values in a multidimensional array. So far, we’ve seen that a primary concern in a multidimensional array is the nesting or level of depth. A general rule is to avoid the iterative approach if the levels exceed two or three at max.

count values in multidimensional array PHP

We explained the reason in one of the articles where we had distinguished iterative and recursive approaches. Here we’ll be using both these approaches and some built-in functions in the context of PHP count values in multidimensional array. So, let’s move to the first option.

Option#1 – Count values in multidimensional array PHP – Iterative Approach

The iterative approach uses iterators, loops to access the array. PHP foreach loop is handy when iterating over an array and could be a good choice if the multidimensional array has at most three levels, as mentioned above. Let’s look at an example.

Example

We have an array of students_electives that contains student names as keys and arrays to keep information about their elective subject. The array has two levels only, and that’s why it is a good use case for an iterative approach.

$students_electives = [
    "Andy" => ["ID"=>"1001", "Elective"=>"Computer Science"],
    "Benjamin" => ["ID"=>"1002", "Elective"=>"Electronics"],
    "Catheline" => ["ID"=>"1003", "Elective"=>"Economics"],
    "Dexter" => ["ID"=>"1004", "Elective"=>"Computer Science"],
    "Eion" => ["ID"=>"1004", "Elective"=>"Computer Science"],
    "Franklin" => ["ID"=>"1005", "Elective"=>"Mathematics"],
    "Gina" => ["ID"=>"1006", "Elective"=>"Chemistry"],
    "Hudson" => ["ID"=>"1007", "Elective"=>"Electronics"],
    "Ira" => ["ID"=>"1008","Elective"=>"Mathematics"],
    "Jessica" => ["ID"=>"1009","Elective"=>"Economics"],
    "Kelvin" => ["ID"=>"1010","Elective"=>"Computer Science"],
    "Liam" =>  ["ID"=>"1011","Elective"=>"Mathematics"],
];

So, the goal is to find the frequency of the elective subjects. Let’s find out.

$resultant = [];
foreach($students_electives as $student=>$elective) {
    //Check if a key has been created for the subject
    if(!isset($resultant[$elective["Elective"]])) {
        //Initiate the count to one for the newly created subject.
        $resultant[$elective["Elective"]] = 1;
    }
 
    else {
        //If a subject reoccurs then increase the count by one.
        $resultant[$elective["Elective"]] += 1;
    }
}
 
print_r($resultant);
 
/*
OUTPUT
Array
(
    [Computer Science] => 4
    [Electronics] => 2     
    [Economics] => 2
    [Mathematics] => 3
    [Chemistry] => 1
)
*/

Voila! The code counts the recurring elective values by incrementing the corresponding key created in the resultant array. Also, observe that we have directly accessed the array at level two using a key/index. Direct access may not be possible every time and particularly if you’ve parsed an XML or JSON response from a server.

So, always make sure to avoid more than three nested loops. Alternatively, there is the recursive approach. Let’s check that out as well. 

Option#2 – Count values in multidimensional array PHP – Recursive Approach

So before we move on to the example, let’s add another elective to every student record in the array. That’s just to make the array more nested and have three levels. The recursive approach is ideal for digging deep into a multidimensional array.


For the recursive approach,  we can use the array_walk_recursive function. Remember that this function access the leaf nodes only. Luckily, the electives are leaf nodes in the students_electives array. That’s why it is better to use this function rather than writing a function of our own.

$students_electives = [
    "Andy" => ["ID"=>"1001", "Elective"=>["Computer Science","Electronics"]],
    "Benjamin" => ["ID"=>"1002", "Elective"=>["Electronics","Mathematics"]],
    "Catheline" => ["ID"=>"1003", "Elective"=>["Economics","Mathematics"]],
    "Dexter" => ["ID"=>"1004", "Elective"=>["Computer Science","Mathematics"]],
    "Eion" => ["ID"=>"1004", "Elective"=>["Computer Science","Economics"]],
    "Franklin" => ["ID"=>"1005", "Elective"=>["Mathematics","Chemistry"]],
    "Gina" => ["ID"=>"1006", "Elective"=>["Chemistry","Biology"]],
    "Hudson" => ["ID"=>"1007", "Elective"=>["Electronics","Digital Logic Design"]],
    "Ira" => ["ID"=>"1008","Elective"=>["Mathematics","Digital Logic Design"]],
    "Jessica" => ["ID"=>"1009","Elective"=>["Economics","Mathematics"]],
    "Kelvin" => ["ID"=>"1010","Elective"=>["Computer Science","Digital Logic Design"]],
    "Liam" =>  ["ID"=>"1011","Elective"=>["Mathematics","Chemistry"]]
];

Example

$resultant = [];
 
array_walk_recursive($students_electives,function($value,$key) use (&$resultant){
    if(!is_numeric($value)) {
        //Initiate the count to one for the newly created subject.
        if(!isset($resultant[$value])) {
            $resultant[$value] = 1;
        }
 
        //If a subject reoccurs then increase the count by one.
        else {
            $resultant[$value] += 1;
        }
    }    
},$resultant);
 
print_r($resultant);
 
/*
OUTPUT
Array
(
    [Computer Science] => 4    
    [Electronics] => 3
    [Mathematics] => 7
    [Economics] => 3
    [Chemistry] => 3
    [Biology] => 1
    [Digital Logic Design] => 3
)
*/

The example works fine. We have a frequency count for all the subjects, and we get this by calling a function only. So, it is a refactored version of what we have seen earlier. One thing to observe is that we have kept is_numeric check in the callback. That’s to filter out the Id as they are leaf nodes and get picked by the array_walk_recursive function while PHP count values in multidimensional array.

Next, let’s see another approach to count values in multidimensional array PHP.

Option#3 – Count values in multidimensional array PHP – Built-In Functions

The example we will see here is a powerful one-liner equivalent to what we have seen in the preceding examples. We have used a chain of calls to several built-in functions. So, let’s see the example first and then break it down for clarity.

Example

print_r(array_count_values(array_merge(...array_column($students_electives,"Elective"))));
 
/*
OUTPUT
Array
(
    [Computer Science] => 4
    [Electronics] => 3
    [Mathematics] => 7
    [Economics] => 3
    [Chemistry] => 3
    [Biology] => 1
    [Digital Logic Design] => 3
)
*/

BreakDown

  • array_column  – Unifies the specified column in an array. So the Electives of all the students are kept in an array.
  • array_merge – This function merges the array received from the array_column into a one-dimensional array.

Notice the … before array_column. This feature is argument unpacking, and it pops the subarrays out. Consequently, these arrays pass to the array_merge in the example. If you need more clarity, try out the example and print the result of these functions to the console one at a time to see the transformation along the way.

Conclusion

That’s it for this article. We’ve seen three different options relating to PHP count values in multidimensional array. The first is the iterative approach followed by the recursive approach. Finally, we explored how to stack some relevant built-in functions for counting values in arrays. We hope you’ve enjoyed it. Stay tuned for more interesting and informative PHP tutorials and articles.


Article Categories

Article Tags

© 2022 Confident.Systems