Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I count the number of element inside an array with value equals a constant? example,

$myArray = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");

how can I directly know how many "Ben" is inside?

share|improve this question

6 Answers

up vote 6 down vote accepted
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
share|improve this answer
thanks for answering. :) – ivory- santos Jul 25 '12 at 9:15

Use array_count_values() function . Check this link http://php.net/manual/en/function.array-count-values.php

share|improve this answer
I know that but does not gives what I want, it returns all the number of same element – ivory- santos Jul 25 '12 at 8:59
@ivory-santos are you sure this method is not helpful ??..check this link codepad.org/Ye2x8uQD – swapnesh Jul 25 '12 at 9:01
@ivory-santos isn't it what you exactly want? – Alexander Larikov Jul 25 '12 at 9:01
not really :) i got the answer, i don't know lately that after counting it is possible to count['Ben']. thanks – ivory- santos Jul 25 '12 at 9:13
@ivory-santos all good :) it happens (at least from my programming experience ..lol) – swapnesh Jul 25 '12 at 9:20

Use array_count_values

$countValues = array_count_values($myArray);

echo $countValues[Ben];

share|improve this answer

try the array_count_values() function

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

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

share|improve this answer

You can do this with array_keys and count.

$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue");

Output:

3
share|improve this answer

Try the PHP function array_count_values.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.