the posted answers are correct for your typical example, but I would like to add another solution that will work no matter how many nested arrays you can create. it iterates over the array recursively and counts all the elements in all subarrays.
it returns the total number of elements in the array. in the second argument, you can specify the reference array that will contain the bill for the unique key in the (nested) array.)
Example:
<?php $deeply_nested = array( 'a' => 'x', 'b' => 'x', 'c' => 'x', 'd' => array( 'a' => 'x', 'b' => 'x', 'c' => array( 'a' => 'x', 'b' => 'x' ), 'e' => 'x' ) ); function count_nested_array_keys(array &$a, array &$res=array()) { $i = 0; foreach ($a as $key=>$value) { if (is_array($value)) { $i += count_nested_array_keys($value, &$res); } else { if (!isset($res[$key]) $res[$key] = 0; $res[$key]++; $i++; } } return $i; } $total_item_count = count_nested_array_keys($deeply_nested, $count_per_key); echo "total count of items: ", $total_item_count, "\n"; echo "count per key: ", print_r($count_per_key, 1), "\n";
leads to:
total count of items: 8 count per key: Array ( [a] => 3 [b] => 3 [c] => 1 [e] => 1 )
Kaii
source share