Reputation: 23
How to specifically count arrays inside of an array? For example:
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
Output should be 3.
Upvotes: 2
Views: 428
Reputation: 47883
Recursively iterate your input array and restart the tally variable upon entering a new level in the array. Every time an array is encountered, add one and recurse. Pass up the tallies from the deeper levels and when the levels are completely traversed, return the top level's cumulative tally.
Code: (Demo)
$array = [10, [[[]],[]], 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12];
function array_tally_recursive(array $array): int {
$tally = 0;
foreach ($array as $item) {
if (is_array($item)) {
$tally += 1 + array_tally_recursive($item);
}
}
return $tally;
}
echo array_tally_recursive($array);
Upvotes: 2
Reputation: 37049
You can use a recursive function for that. Let me give you an example:
<?php
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ];
$arrayCount = 0; # this variable will hold count of all arrays found
# Call a recursive function that starts with taking $array as an input
# Recursive function will call itself from within the function
countItemsInArray($array);
function countItemsInArray($subArray) {
# access $arrayCount that is declared outside this function
global $arrayCount;
# loop through the array. Skip if the item is NOT an array
# if it is an array, increase counter by 1
# then, call this same function by passing the found array
# that process will continue no matter how many arrays are nested within arrays
foreach ($subArray as $x) {
if ( ! is_array($x) ) continue;
$arrayCount++;
countItemsInArray($x);
}
}
echo "Found $arrayCount arrays\n";
https://rextester.com/SOV87180
Here's how the function would operate.
[ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
is sent to countItemsInArray
function[1, 2, 3, ['hi', 7]
.Remember, this same function called with the entire array is not dead. It's just waiting for this countItemsInArray([1, 2, 3, ['hi', 7]])
to be done
countItemsInArray(['hi', 7])
is called.Remember that countItemsInArray with the full array as the parameter AND
countItemsInArray([1, 2, 3, ['hi', 7]]) are now waiting for countItemsInArray(['hi', 7])
to be done
countItemsInArray([1, 2, 3, ['hi', 7]])
countItemsInArray([1, 2, 3, ['hi', 7]])
recognizes that it has nothing more to evaluate. Control is given back to countItemsInArray($array).
countItemsInArray($array) evaluates 12 and determines that's not an array either. So, it ends its work.
Then, echo echoes out that array count is 3.
Upvotes: 2