67

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?

feeela
  • 29,399
  • 7
  • 59
  • 71
Ivo San
  • 1,233
  • 4
  • 16
  • 26

10 Answers10

145
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
Rajat Singhal
  • 11,234
  • 5
  • 38
  • 56
  • 12
    what if the array is multidimensional? – Oki Erie Rinaldi Sep 16 '14 at 04:41
  • 15
    @OkiErieRinaldi then OP needs to update the question. – James Mar 11 '15 at 01:45
  • 1
    @James Can you please give me a reference ? – Oki Erie Rinaldi Mar 11 '15 at 01:47
  • 2
    @OkiErieRinaldi: First SO result I found on google: [Count specific values in multidimensional array](http://stackoverflow.com/questions/11558397/count-specific-values-in-multidimensional-array/11558780) - see if that works for multidimensionals. – Cullub Feb 02 '16 at 19:36
  • @cullub it works for 2 levels depth. if the array is deeper, we have to add more iteration. I made it by building recursive function. – Oki Erie Rinaldi Feb 03 '16 at 02:02
  • Nice. Just posting that link for future Googlers who are looking for a multidimensional solution. – Cullub Feb 03 '16 at 04:41
  • 6
    if you count element which is not in array, it will show `Notice: Undefined index` – Elyor Sep 08 '16 at 05:54
  • @Elyor do you know how I can fix this?? In my case I need to output 4 variables for some javascript. I already tested with `isset($codes['T'])? $codes['T']:'' ` where $codes is the = array_count_values( – alex Feb 06 '18 at 11:58
  • For float values get this: `Warning: array_count_values(): Can only count STRING and INTEGER values!` what's solution? – Nabi K.A.Z. Oct 18 '18 at 19:41
42

You can do this with array_keys and count.

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

Output:

3
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Oliver A.
  • 2,870
  • 2
  • 19
  • 21
  • 2
    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 – mickmackusa Nov 15 '17 at 04:16
  • 5
    I tested this code vs the code @Rajat Singhal posted. [PHP-Sandbox](http://sandbox.onlinephpfunctions.com/code/aee8e6a978c45a3369fd60984ad4da3244812bfe). 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) – miile7 Jun 06 '18 at 08:30
  • 2
    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 – fbastien Dec 03 '19 at 16:22
17

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
    
Vishal Kumar Sahu
  • 1,232
  • 3
  • 15
  • 27
9

Use the array_count_values function.

$countValues = array_count_values($myArray);

echo $countValues["Ben"];

Community
  • 1
  • 1
Rikesh
  • 26,156
  • 14
  • 79
  • 87
6

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

swapnesh
  • 26,318
  • 22
  • 94
  • 126
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
Leo
  • 51
  • 1
  • 2
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

Doc
  • 5,078
  • 6
  • 52
  • 88
1

Try the PHP function array_count_values.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
nairbv
  • 4,045
  • 1
  • 24
  • 26
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)
frosty
  • 2,559
  • 8
  • 37
  • 73
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%)!

dhc
  • 647
  • 8
  • 17