Count elements in each helper array in php

An example from php.net contains the following

<?php $food = array('fruits' => array('orange', 'banana', 'apple'), 'veggie' => array('carrot', 'collard', 'pea')); // recursive count echo count($food, COUNT_RECURSIVE); // output 8 // normal count echo count($food); // output 2 ?> 

How can I get the number of fruits and the number of veggies regardless of the $ food array (output 3)?

+4
source share
4 answers

You can do it:

 echo count($food['fruits']); echo count($food['veggie']); 

If you want a more general solution, you can use the foreach loop:

 foreach ($food as $type => $list) { echo $type." has ".count($list). " elements\n"; } 
+7
source

You can use this function to count non-empty array values โ€‹โ€‹recursively.

 function count_recursive($array) { if (!is_array($array)) { return 1; } $count = 0; foreach($array as $sub_array) { $count += count_recursive($sub_array); } return $count; } 

Example:

 $array = Array(1,2,Array(3,4,Array(5,Array(Array(6))),Array(7)),Array(8,9)); var_dump(count_recursive($array)); // Outputs "int(9)" 
+2
source

Just type count() on these keys.

 count($food['fruit']); // 3 count($food['veggie']); // 3 
0
source

Could you be a little lazy, not a spotlight with a running score twice and pick up your parents.

 // recursive count $all_nodes = count($food, COUNT_RECURSIVE); // output 8 // normal count $parent_nodes count($food); // output 2 echo $all_nodes - $parent_nodes; // output 6 
0
source

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


All Articles