How to Count Array Elements, Unique Values, and Occurrences in PHP
This guide explains how to use PHP's built‑in functions like count(), array_count_values(), and array_filter()—along with loops—to determine the total number of elements, count distinct values, and find the frequency of a specific item in an array.
1. Counting the total number of array elements
PHP provides the count() function, which returns the number of elements in an array.
$fruits = array("apple", "orange", "banana", "pear");
echo count($fruits); // outputs 4The example creates an array with four items and prints 4 using count().
2. Counting distinct elements in an array
To obtain the number of occurrences for each unique value, use array_count_values(). It returns a new array where the keys are the distinct elements and the values are their respective counts.
$fruits = array("apple", "orange", "banana", "pear", "apple", "apple");
$count_fruits = array_count_values($fruits);
print_r($count_fruits); Array (
[apple] => 3
[orange] => 1
[banana] => 1
[pear] => 1
)The output shows that "apple" appears three times, while the other fruits appear once each.
3. Counting the occurrences of a specific element
There are several ways to count how many times a particular value, such as "apple", appears.
Method A – Using a foreach loop :
$fruits = array("apple", "orange", "banana", "pear", "apple", "apple");
$count_apple = 0;
foreach ($fruits as $fruit) {
if ($fruit == "apple") {
$count_apple++;
}
}
echo $count_apple; // outputs 3Method B – Using array_filter with an anonymous function :
$fruits = array("apple", "orange", "banana", "pear", "apple", "apple");
$count_apple = count(array_filter($fruits, function($fruit) {
return $fruit == "apple";
}));
echo $count_apple; // outputs 3Both approaches yield the same result, and you can choose the one that best fits your coding style or performance needs.
In summary, PHP offers multiple built‑in functions ( count(), array_count_values(), array_filter()) and looping constructs to efficiently count array elements, distinct values, or specific occurrences, allowing developers to select the most appropriate method for their scenario.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
