0

I'm having very simple issue. I have array

 $a = array('dog', 'dog', 'dog', 'mouse', 'mouse','mouse', 'cat','cat');

How to count how many elements called 'dog' I have ? I tried count() function , i know it's not good because count doesn't look into array only counts number of elements.

So for example answer for my issue would be :

 dog = 3 
 mouse = 3
 cat = 2

4 Answers 4

4

Use array_count_values():

print_r(array_count_values($a));

Array
(
    [dog] => 3
    [mouse] => 3
    [cat] => 2
)

$count = array_count_values($a);
echo $count['dog']; // prints 3
Sign up to request clarification or add additional context in comments.

Comments

2

you have to use array-count-values

http://www.php.net/manual/en/function.array-count-values.php

print_r(array_count_values($a));

Array
(
    [dog] => 3
    [mouse] => 3
    [cat] => 2
)

Comments

2

You're looking for the array_count_values function.

$a = array('dog', 'dog', 'dog', 'mouse', 'mouse','mouse', 'cat','cat');

$counted = array_count_values($a);

$numberOfDogs = $counted['dog'];

Comments

2

array_count_values();

Given your input:

$a = array('dog', 'dog', 'dog', 'mouse', 'mouse','mouse', 'cat','cat');
$var = array_count_values($a);
var_dump($var);

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.