Monday, 13 August 2018

How to Count Occurrence of an Array Element in PHP?

Problem:

You have an array (see the following array) which has some repeating elements. You want to count the number of occurrence of a specific element(for ex. Mark).
1
$friends = array("Mark", "Caroline", "Douglas", "Brian", "Mark", "John", "John");

Solution:

To find the number of occurrence of an array element, follow the steps below-

Step 1: Use array_count_values() function to count number of occurrence of all elements.

If you use the above array as parameter in the array_count_values()function, it will return an associative array whose keys are the values of the above array and values are the number of occurrence of each element of the above array.

Step 2: Output the number of occurrence using array[‘key’]

To show the number of occurrence of an element(ex. Mark), use Mark as key in the associative array that we got in the step 1.
See the complete example below-
1
2
3
4
5
<?php
$friends = array("Mark", "Caroline", "Douglas", "Brian", "Mark", "John");
$friends_count = array_count_values($friends);
echo $friends_count["Mark"];
?>
Output:Mark occurs 2 times
How it works:array_count_values() function returns an associative array with the number of occurrence of each element. If you print the $friends_count, you’ll see the following-
The above array outputs occurrence of each element. To display the occurrence number of Mark, we used $friends_count[“Mark”] in the code above.

0 comments:

Post a Comment