How to count the number of elements of a multidimensional array without using a loop in PHP?

I have an array as shown below:

$array = Array ( '0' => Array ( 'num1' => 123, 'num2' => 456, ), '1' => Array ( 'num3' => 789, 'num4' => 147, ), '2' => Array ( 'num5' => 258, 'num6' => 369, 'num7' => 987, ), ); 

I want to count the number of elements, i.e. num1 to num7 means i want output 7 . How can I do this without using a loop?

+5
source share
2 answers

use the array_sum and array_map function together.

try below solution:

 $array = Array ( '0' => Array ( 'num1' => 123, 'num2' => 456, ), '1' => Array ( 'num3' => 789, 'num4' => 147, ), '2' => Array ( 'num5' => 258, 'num6' => 369, 'num7' => 987, ), ); echo $total = array_sum(array_map("count", $array)); 

Output

 7 

an alternative way could be:

 echo count($array, COUNT_RECURSIVE) - count($array); //output: 7 
+5
source

Using the array_sum function

 $totalarray = array_sum(array_map("count", $array)); 

Using Foreach Loop

 $count = 0; foreach( $array as $arrayVal){ $count += count($arrayVal); } 
+2
source

Source: https://habr.com/ru/post/1246843/


All Articles