Craigjb
Craigjb

Reputation: 59

Count elements in each sub array in php

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

Upvotes: 6

Views: 15231

Answers (4)

tristanbailey
tristanbailey

Reputation: 4605

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

Upvotes: 5

Ulver
Ulver

Reputation: 905

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

Upvotes: 2

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

Just call count() on those keys.

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

Upvotes: 2

jh314
jh314

Reputation: 27802

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

Upvotes: 14

Related Questions