Is is to possible to get how many 'a' are in a开发者_运维技巧rray?
$array = array( 'a', 'a', 'a', 'a', 'b', 'b', 'c' );
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
)
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.";
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.
精彩评论