OneBite.Dev - Coding blog in a bite size

Count The Number Of Occurrences Of A Specific Element In An Array In PHP

Code snippet for how to Count The Number Of Occurrences Of A Specific Element In An Array In PHP with sample and detail explanation

Working with arrays is a common task in PHP development. One common requirement is to count the number of occurrences of a specific element in a given array. This article serves as a quick guide to help you achieve this in PHP.

Code snippet

To count the number of occurrences of a specific element in an array, you can use the array_count_values() function in PHP. Here’s a simple snippet to illustrate this:

//Define your array
$array = array("apple", "orange", "apple", "banana", "apple", "orange", "apple");

//Use array_count_values()
$count = array_count_values($array);

//Print the count of a specific element
echo $count["apple"];

This piece of code will output 4 which means the “apple” string occurred 4 times in the given array.

Code Explanation

Firstly, we declare an array that contains some fruits, there are multiple occurrences of the “apple” and “orange” strings.

$array = array("apple", "orange", "apple", "banana", "apple", "orange", "apple");

Next, we use array_count_values() function which returns an associative array where the keys are the original array’s values and the value are the number of occurrences of those values in the array. This function simply counts the appearance of each value in the input array.

$count = array_count_values($array);

Lastly, we print the count of the specific element we want to find out. In this case, we are checking the number of times “apple” occurs in the array.

echo $count["apple"];

This piece of code will print the number 4, which is the count of “apple” in the array. This way, you easily get the count of occurrences of a specific element in an array in PHP.

php