Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Count Array Columns

Tags:

arrays

php

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.

like image 609
Saint Robson Avatar asked Dec 30 '25 05:12

Saint Robson


2 Answers

...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));
like image 183
peterm Avatar answered Jan 01 '26 17:01

peterm


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 )

like image 20
Suchit kumar Avatar answered Jan 01 '26 18:01

Suchit kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!