Last Updated on August 5, 2021 by Roshan Parihar
In this tutorial, learn how to count occurrence of value in array using PHP. The short answer is to use the PHP array_count_values() Function of PHP that takes a single argument as an array.
You can also find the number of times the specified element is present in an array. Let’s find out the different methods and examples given below to learn.
Using array_count_values() to Count Occurrence of Value in Array in PHP
To count the occurrence of value in an array, you can use the array_count_values()
function. It takes a single argument that is the array or array variable to pass to the function. The function counts the occurrences of all the elements present in an array in PHP.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myArr = array("Badminton", "Cricket", "Hockey", "Volley Ball", "Golf", "Hockey", "Cricket"); //Count all the values in array $newArr = array_count_values($myArr); //Print result print_r($newArr); ?> |
Output
The above example shows the output that display the number of occurrences of each element present in an array.
How to Count Occurrence of Specific Value in Array in PHP
When you have a given element to count its occurrence in an array, you can use the array_keys()
inside the count()
in PHP. You will get the result that displays the number of times the specified element is present in an array.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myArr = array("Badminton", "Cricket", "Hockey", "Volley Ball", "Golf", "Hockey", "Cricket"); //Count specific value in an array using array_keys() $newArr = count(array_keys($myArr, "Cricket")); //Print result print_r($newArr); ?> |
Output
The above example shows that the specified element is present in an array for 2 times.
Get Number of Element Present in an Array Using For Loop in PHP
In addition to the above methods, you can also get the number of elements present in an array using foreach loop of PHP. You need to use a counter and initiate it with zero. It also requires using the if condition of PHP and match the given element with every element of an array in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php //Declare an array in PHP $myArr = array("Badminton", "Cricket", "Hockey", "Volley Ball", "Golf", "Hockey", "Cricket"); //Given value $myVal = "Cricket"; //Get number of times element present in an array $i = 0; foreach($myArr as $value) { if($value === $myVal){ $i++; } } //Print result print_r($i); ?> |
Output
The output given in the above example shows that there are two ‘Cricket’ elements present in an array.
You May Also Like to Read