How to Count Array Elements in PHP Using count(), array_count_values() and array_filter()
This article explains how to use PHP's count(), array_count_values(), and array_filter() functions, as well as loops, to count total array elements, distinct values, and specific element occurrences, providing code examples for each method.
In PHP, arrays are a fundamental data type, and counting elements or occurrences can be done with built-in functions. This guide shows how to count the total number of elements, the number of distinct elements, and the 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 4The code defines an array $fruits with four items and uses count() to output the value 4.
2. Counting distinct elements in an array
The array_count_values() function returns an associative array where each key is a distinct 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);The result is:
Array (
[apple] => 3
[orange] => 1
[banana] => 1
[pear] => 1
)This shows that "apple" appears three times, while "orange", "banana", and "pear" each appear once.
3. Counting the occurrences of a specific element
You can use array_count_values() together with array indexing, a foreach loop, or array_filter() with an anonymous function.
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 3Using 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 count how many times "apple" appears in the original $fruits array, resulting in the value 3.
In summary, PHP provides several ways— count() , array_count_values() , foreach loops, and array_filter() with anonymous functions—to count array elements, and the choice depends on the specific scenario and performance considerations.
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.