PHP - count specific array values

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?


Solution 1:

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

Solution 2:

You can do this with array_keys and count.

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

Output:

3

Solution 3:

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
    

Solution 4:

Use the array_count_values function.

$countValues = array_count_values($myArray);

echo $countValues["Ben"];

Solution 5:

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