Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the item from an array in PHP [duplicate]

Tags:

arrays

php

How can I count in a multidimensional array the number of element with a special condition ?

Array
(
    [0] => Array
        (
            [item] => 'Banana'
        )

    [1] => Array
        (
            [item] => 'Banana'

        )

    [2] => Array
        (
            [item] => 'Cherry'
        )

    [3] => Array
        (
            [item] => 'Apple'

        )
)

For example, for this array I should find 2 for Banana.

Si I tried:

$i=0;
foreach($array as $arr) {
    if($arr[item]=='Banana') { $i++; }
}

Is there a better solution please ?

Thanks.

like image 730
F__M Avatar asked Nov 30 '25 07:11

F__M


1 Answers

Method 1:

Using built-in functions - array_column and array_count_values:

print_r(array_count_values(array_column($arr,'item')));

Method 2:

Using foreach with simple logic of making your fruit as key and its count as value:

$arr = [
["item"=>"Banana"],
["item"=>"Banana"],
["item"=>"Cherry"],
["item"=>"Apple"]
];

$countArr = [];

foreach ($arr as $value) {
    $item = $value['item'];
    if(array_key_exists($item, $countArr))   // If key exists, increment its value
        $countArr[$item]++;
    else                                     // Otherwise, assign new key
        $countArr[$item] = 1;
}

print_r($countArr);

Final result in both case would be:

Array
(
    [Banana] => 2
    [Cherry] => 1
    [Apple] => 1
)

So when you want Banana's count, you can get it like this:

echo $countArr['Banana'];
like image 74
Thamilhan Avatar answered Dec 02 '25 20:12

Thamilhan