How to Count Array Elements, Unique Values, and Occurrences in PHP
This guide explains how to use PHP's count(), array_count_values(), and array_filter() functions, along with loops, to count total elements, distinct values, and specific element occurrences in an array, providing clear code examples for each method.
In PHP, arrays are a fundamental data type, and counting elements can be done with built-in functions. The article covers three main tasks: counting total elements, counting distinct elements, and counting occurrences of a specific element.
1. Counting the total number of array elements
The count() function returns the number of elements in an array.
$fruits = array("apple", "orange", "banana", "pear");
echo count($fruits); // outputs 42. Counting distinct elements in an array
The array_count_values() function returns a new array where each key is a unique value from the original array and each value is the number of times that key appears.
$fruits = array("apple", "orange", "banana", "pear", "apple", "apple");
$count_fruits = array_count_values($fruits);
print_r($count_fruits);
/* Output:
Array (
[apple] => 3
[orange] => 1
[banana] => 1
[pear] => 1
) */3. Counting occurrences of a specific element
One approach uses a foreach loop to iterate the array and increment a counter when the target value is found.
$fruits = array("apple", "orange", "banana", "pear", "apple", "apple");
$count_apple = 0;
foreach ($fruits as $fruit) {
if ($fruit == "apple") {
$count_apple++;
}
}
echo $count_apple; // outputs 3Another approach combines array_filter() with an anonymous function to keep only the desired elements, then uses count() to get the total.
$fruits = array("apple", "orange", "banana", "pear", "apple", "apple");
$count_apple = count(array_filter($fruits, function($fruit) {
return $fruit == "apple";
}));
echo $count_apple; // outputs 3In summary, PHP offers several ways— count(), array_count_values(), foreach loops, and array_filter() with anonymous functions—to count array elements, distinct values, or specific occurrences, allowing developers to choose the most suitable method for their needs.
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.
