Saint Robson
Saint Robson

Reputation: 5525

PHP Count Array Columns

I have this PHP array :

$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', NULL));

if I use this function :

$rows = count($food);

of course the result will be 2, but how to get number of array columns? so, I'm expecting 3 as a value of fruits and veggie columns. even though veggie has NULL.

Upvotes: 3

Views: 15492

Answers (5)

Sree
Sree

Reputation: 1529

$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', NULL));
$array = array_map('count', $food);

Upvotes: 2

Suchit kumar
Suchit kumar

Reputation: 11859

You can try This: array_map with count.

<?php 
 $food = array('fruits' => array('orange', 'banana', 'apple'),
        'veggie' => array('carrot', 'collard', NULL));
 $typeTotals = array_map("count", $food);
echo "<pre>";
print_r($typeTotals);

OUTPUT:

Array ( [fruits] => 3 [veggie] => 3 )

Upvotes: 5

Calvin Coderes
Calvin Coderes

Reputation: 27

You can try this :

$food = array('fruits' => array('orange', 'banana', 'apple'),
                'veggie' => array('carrot', 'collard', NULL));

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

However it would only work if you know the element e.g. 'fruits'.

Upvotes: 1

peterm
peterm

Reputation: 92795

...I mean, if the columns are always the same, then why should we loop it as many as rows?

If the number of columns is always the same and you have at least one element in your $food array you can just probe the first/current element with current()

$columns = count(current($food));

Upvotes: 7

user2182349
user2182349

Reputation: 9782

This approach will create an array of counts, by type:

$rows = [];
foreach ($food as $type => $items) {
    $rows[$type] = count($items);
]

Upvotes: 1

Related Questions