F__M
F__M

Reputation: 1598

Count the item from an array in 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.

Upvotes: 3

Views: 78

Answers (2)

Rasclatt
Rasclatt

Reputation: 12505

Use array_count_values(), it is pretty straight forward:

foreach($array as $arr) {
    $new[]  =   $arr['item'];
}

print_r(array_count_values($new));

On a side note, there isn't anything wrong with your approach, unless you want to count all values. Also on a side note, I think you'll find a foreach() will eek out a slightly faster time than array_column(), especially on a large array.

Upvotes: 0

Thamilhan
Thamilhan

Reputation: 13313

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'];

Upvotes: 2

Related Questions