4

Is is to possible to get how many 'a' are in array?

$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
0

3 Answers 3

11

array_count_values is what you need

<?php
$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [a] => 4
    [b] => 2
    [c] => 1
)
Sign up to request clarification or add additional context in comments.

Comments

4

Since you're just looking for a values, you could also use array_keys:

$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
$count = count(array_keys($array, 'a', true));
echo "Found $count letter a's.";

Comments

2

Haim is correct. However I have had some speed issues with array_count_values before. So if you already know what value you are checking for, and don't need the others. A loop and counter can be faster. I'd benchmark.

EDIT

That is, unless the array is smaller than 1000-10,000 items. Then it is probably too small to matter.

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.