Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count elements in each sub array in php

Tags:

arrays

php

count

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)?

like image 632
Craigjb Avatar asked Jul 05 '13 20:07

Craigjb


People also ask

How do I count items in an array PHP?

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.

What is the use of Array_count_values () in PHP explain with example?

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.

What is recursive count in PHP?

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.


2 Answers

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";
}
like image 138
jh314 Avatar answered Oct 06 '22 23:10

jh314


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
like image 21
tristanbailey Avatar answered Oct 06 '22 23:10

tristanbailey