How to Count Occurrence of Value in Array in PHP

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.

Output

Array ( [Badminton] => 1 [Cricket] => 2 [Hockey] => 2 [Volley Ball] => 1 [Golf] => 1 )

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.

Output

2

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.

Output

2

The output given in the above example shows that there are two ‘Cricket’ elements present in an array.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.