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?
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.
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 .
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.
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.
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben"); $counts = array_count_values($array); echo $counts['Ben'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With