PHP Count Array Columns

11,541

Solution 1

...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));

Solution 2

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 )

Solution 3

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

Solution 4

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

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

Solution 5

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'.

Share:
11,541

Related videos on Youtube

Saint Robson
Author by

Saint Robson

Updated on October 15, 2022

Comments

  • Saint Robson
    Saint Robson over 1 year

    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.

  • Saint Robson
    Saint Robson over 8 years
    Hi bro, thanks for your answer. but, is there any other ways to count the columns without foreach loop? I mean, if the columns are always the same, then why should we loop it as many as rows?
  • Kevin
    Kevin over 8 years
    i would answer this way also, i'd also add max if the columns are jagged. echo max(array_map('count', $food));, anyway +1
  • Suchit kumar
    Suchit kumar over 8 years
    @Ghost but i guess he is expecting both the keys in output.
  • LUISAO
    LUISAO over 2 years
    Thank you @Kevin. It is just what i want to do! Thank you Suchit Kumar!