An example from php.net provides 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 veggies independently from the $food array (output 3)?
We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array. If we do not set the value for a variable, it returns 0.
The array_count_values() function is used to count all the values inside an array. In other words, we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array. Parameters: This function accepts a single parameter $array.
value. An array or Countable object. mode. 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.
You can do this:
echo count($food['fruits']);
echo count($food['veggie']);
If you want a more general solution, you can use a foreach loop:
foreach ($food as $type => $list) {
echo $type." has ".count($list). " elements\n";
}
Could you be a little lazy, rather than a foreach with a running count twice and take away the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With