0

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:

$array = array_count_values(array_column($arr,'item'))
echo $array['Banana'];

But it's not working.

Thanks.

4
  • 1
    chk error reporting, its working fine, getting Array ( [Banana] => 2 [Cherry] => 1 [Apple] => 1 ), i hope this is typo $array = array_count_values(array_column($arr,'item')) missing semi colon Commented Jan 20, 2017 at 14:41
  • 1
    or chk your php version, maybe you are using 5.4 Commented Jan 20, 2017 at 14:47
  • @devpro: my PHP version is 5.6.29. Commented Jan 20, 2017 at 14:52
  • than this will work, as working on my side. Commented Jan 20, 2017 at 15:07

1 Answer 1

2

Another option could be filtering your array with array_filter according to the requirements, if you're just searching for one keyword.

$key = 'Banana'; 
$bananas = array_filter ($arr, function($value) use($key){
    return $value['item'] == $key;
});

$cnt_bananes = count($bananas); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.