Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - count specific array values

Tags:

arrays

php

count

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?

like image 971
Ivo San Avatar asked Jul 25 '12 08:07

Ivo San


People also ask

How do I count items in an array PHP?

We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array. If we do not set the value for a variable, it returns 0.

How do you count the number of specific numbers in an array?

To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .

How do I count the number of repeated numbers in an array in PHP?

array_count_values() function in PHP The array_count_values() function returns an array with the number of occurrences for each value. It returns an associative array. The returned array has keys as the array's values, whereas values as the count of the passed values.

What functions count elements in an array?

The count() and sizeof() both functions are used to count all elements in an array and return 0 for a variable that has been initialized with an empty array. These are the built-in functions of PHP. We can use either count() or sizeof() function to count the total number of elements present in an array.


1 Answers

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben"); $counts = array_count_values($array); echo $counts['Ben']; 
like image 100
Rajat Singhal Avatar answered Sep 22 '22 15:09

Rajat Singhal