[php] 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?

This question is related to php arrays count

The answer is


Use the array_count_values function.

$countValues = array_count_values($myArray);

echo $countValues["Ben"];


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)

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%)!


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


You can do this with array_keys and count.

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

Output:

3

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

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
    

Try the PHP function array_count_values.


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


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to count

Count the Number of Tables in a SQL Server Database SQL count rows in a table How to count the occurrence of certain item in an ndarray? Laravel Eloquent - distinct() and count() not working properly together How to count items in JSON data Powershell: count members of a AD group How to count how many values per level in a given factor? Count number of rows by group using dplyr C++ - how to find the length of an integer JPA COUNT with composite primary key query not working