69

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?

0

10 Answers 10

146
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
Sign up to request clarification or add additional context in comments.

9 Comments

what if the array is multidimensional?
@OkiErieRinaldi then OP needs to update the question.
@James Can you please give me a reference ?
@OkiErieRinaldi: First SO result I found on google: Count specific values in multidimensional array - see if that works for multidimensionals.
if you count element which is not in array, it will show Notice: Undefined index
|
43

You can do this with array_keys and count.

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

Output:

3

3 Comments

This is the best answer because it doesn't bother php to count all occurrences of all values, it just returns the qualifying keys and counts them in a way which will never throw a Notice. In other words, echo count(array_keys($array, "purple")); prints 0 with no Notice This is a superior / cleaner approach versus array_count_values(). +1
I tested this code vs the code @Rajat Singhal posted. PHP-Sandbox. In PHP 7 the count(array_keys()) solution always is faster. In PHP 5.6 the array_count_values() version is faster for arrays with less different elements. All in all both functions are quite fast (at least for the arrays I was testing)
IMO this is the best answer also because it works with arrays containing values other than strings and integers whereas array_count_values() would complain about it. +1
18

To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value-

    <?php
    
    $list = [
      ['id' => 1, 'userId' => 5],
      ['id' => 2, 'userId' => 5],
      ['id' => 3, 'userId' => 6],
    ];

    $userId = 5;
    
    echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
    

Comments

9

Use the array_count_values function.

$countValues = array_count_values($myArray);

echo $countValues["Ben"];

Comments

6

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

5 Comments

I know that but does not gives what I want, it returns all the number of same element
@ivory-santos are you sure this method is not helpful ??..check this link codepad.org/Ye2x8uQD
@ivory-santos isn't it what you exactly want?
not really :) i got the answer, i don't know lately that after counting it is possible to count['Ben']. thanks
@ivory-santos all good :) it happens (at least from my programming experience ..lol)
5
define( 'SEARCH_STRING', 'Ben' );

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

$count = count(array_filter($myArray,function($value){return SEARCH_STRING === $value;}));

echo $count, "\n";

Output:

3

Comments

2

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

Comments

1

Try the PHP function array_count_values.

Comments

1

If you want to count ALL the same occurences inside the array, here's a function to count them all, and return the results as a multi-dimensional array:

function countSame($array) {

$count = count($array);
$storeArray = array();
while ($count > 0) {
$count--;

if ($array[$count]) {
$a = $array[$count];
$counts = array_count_values($array);
$counts = $counts[$a];
$tempArray = array($a, $counts);
array_push($storeArray, $tempArray);

$keys = array_keys($array, $a);
foreach ($keys as $k) {
unset($array[$k]);
} //end of foreach ($keys as $k)
} //end of if ($array[$count])

} //end of while ($count > 0)

return $storeArray;

} //end of function countSame($array)

Comments

1

array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:

function arrayCountValues($arr) {
  $vals = [];
  foreach ($arr as $val) { array_push($vals,strval($val)); }
  $cnts = array_count_values($vals);
  arsort($cnts);
  return $cnts;
}

Note that I return $cnts with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.

I tested a version which looped, creating an array of counts rather than using array_count_values, and this turned out to be more efficient (by maybe 8-10%)!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.