phpcountarray-key-existsarray-sum

Count specific values of PHP Array that has no column assignments


I need to display a count of the no of car makes.

$array = array(
                array(1,'Benz'),
                array(3,'Toyota'), 
                array(4,'Mazda'),
                [2,'VW'],
                [5,'Mazda']
            );


$count = array_count_values(array_column($array, <what do I use here?>;

print_r($count)

Solution

  • You can use number (0,1,2, etc) as second argument:

    $array = array(
                    array(1,'Benz'),
                    array(3,'Toyota'), 
                    array(4,'Mazda'),
                    [2,'VW'],
                    [5,'Mazda']
                );
    
    
    $count = array_count_values(array_column($array, 1));
    
    print_r($count);
    

    Which will output (with Mazda=>2 as expected)

    Array
    (
        [Benz] => 1
        [Toyota] => 1
        [Mazda] => 2
        [VW] => 1
    )