Count total number of items in nested arrays in PHP

Today I was working on some code that had arrays structured like this:

$foo = [
	'a' => [ 1, 2, 3, 4 ],
	'b' => [ 5, 6, 7 ],
];

I needed to calculate the total number of items in the nested arrays. I didn’t find a PHP function to help me with that but I came up with this idea:

$total_count = array_sum( array_map( 'count', $foo ) ); // This returns 7.

How this works

The array_map( 'count', $foo ) part replaces the subarrays in $foo with the result of calling count()on them:

$subarray_counts = array_map( 'count', $foo );
var_dump( $subarray_counts );

/*
 * Result:
 *
 * array(2) {
 * 'a' =>
 * int(4)
 * 'b' =>
 * int(3)
 * }
 */

The array_sum() function then calculates the sum of these item counts.

Please let me know if you found this idea useful! 🙂