Count elements in each sub array in php

12,546

Solution 1

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";
}

Solution 2

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

Solution 3

You can use this function count the 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)"

Solution 4

Just call count() on those keys.

count($food['fruit']); // 3
count($food['veggie']); // 3
Share:
12,546
Craigjb
Author by

Craigjb

Updated on June 05, 2022

Comments

  • Craigjb
    Craigjb almost 2 years

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