我如何计算整个php数组的所有元素?

   $players = array(
                        array('Lionel Messi', 'Luis Suarez', 'Neymar Jr'),
                        array('Ivan Rakitic', 'Andres Iniesta', 'Sergio Busquets'),
                        array('Gerrard Pique', 'Mascherano', 'Denis Suarez', 'Jordi Alba'),
                        array('MATS'),
                        array('Arda Turan', 'Munir El Hadadi', 'Umtiti')
                        );

Now i am trying to echo the number of all the elements within the boundary of this array $players. For example, there are 3 elements in the first, 3 in the second. There are 4 elements in the third, 1 element in the 4th and 3 elements in the last one. Altogether these elements are 14 elements. Now i want to display 'Total Players: 14'. I can show the number of categories (5) using count() function but can't count the total elements(14). I tried different approaches but couldn't succeed.

The native count() method can do that.

$count = count($players, COUNT_RECURSIVE) - count($players);

Because the recursive count will also count the number of $player groups you have, you have to subtract that number from the recursive count.

From the php documentation for count:

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.

Declare a variable initialised to 0 to accumulate the number of elements. Then, iterate the first array (which contains the other arrays), and for each element (which is also an array) use count() to obtain the number of elements and add that value to the accumulator variable.

$num_players = 0;

foreach($players as $row) {
  $num_players += count($row);
}

count() should be able to do this for you directly, using the COUNT_RECURSIVE flag:

$playerCount = count($players, COUNT_RECURSIVE) - count($players);
// $playerCount is now equal to 14

The subtraction of the normal count is because counting recursively adds the keys of the outer array in to the sum of elements, which just needs to be subtracted from the recursive count.

$count=0;
foreach($players as $row) $count+=count($row);

$count is now 14.

Live demo

You can use:

count($array, COUNT_RECURSIVE);

check count manual

One other way, pretty self-explanatory:

$count = array_sum(array_map('count', $players));