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 );
/*
* Result of print_r( $subarray_counts ):
*
* Array
* (
* [a] => 4
* [b] => 3
* )
*/
The array_sum()
function then calculates the sum of the values in the resulting array (each being a number of items contained in a given subarray):
$total_count = array_sum( $subarray_counts );
/*
* Result of print_r( $total_count ): 7
*/
Please let me know if you found this idea useful! 🙂
Leave a Reply