How to Count Elements in Array PHP: Simple Guide
In PHP, you can count the number of elements in an array using the
count() function. Just pass your array as the argument to count(), and it returns the total number of elements.Syntax
The basic syntax to count elements in an array is:
count(array, mode)- array: The array you want to count elements in.
- mode (optional): Use
COUNT_NORMAL(default) to count only top-level elements, orCOUNT_RECURSIVEto count all elements including nested arrays.
php
count(array $array, int $mode = COUNT_NORMAL): int
Example
This example shows how to count elements in a simple array and a nested array using count().
php
<?php $fruits = ['apple', 'banana', 'cherry']; $nested = ['a', ['b', 'c'], 'd']; // Count top-level elements echo count($fruits) . "\n"; // Outputs 3 // Count top-level elements in nested array echo count($nested) . "\n"; // Outputs 3 // Count all elements recursively echo count($nested, COUNT_RECURSIVE) . "\n"; // Outputs 5 ?>
Output
3
3
5
Common Pitfalls
One common mistake is expecting count() to count elements inside nested arrays by default. It only counts the top-level elements unless you use COUNT_RECURSIVE. Also, passing a variable that is not an array will return 1 or 0, which can be confusing.
Example of wrong and right usage:
php
<?php $notArray = "hello"; // Wrong: expecting count of characters echo count($notArray) . "\n"; // Outputs 1, not length of string // Right: use strlen() for strings echo strlen($notArray) . "\n"; // Outputs 5 // Wrong: counting nested elements without recursive mode $nested = [1, [2, 3]]; echo count($nested) . "\n"; // Outputs 2 // Right: count recursively echo count($nested, COUNT_RECURSIVE) . "\n"; // Outputs 3 ?>
Output
1
5
2
3
Quick Reference
| Function | Description |
|---|---|
| count(array) | Returns number of top-level elements in array |
| count(array, COUNT_RECURSIVE) | Counts all elements including nested arrays |
| strlen(string) | Returns length of a string (not for arrays) |
Key Takeaways
Use
count() to get the number of elements in an array in PHP.By default,
count() counts only top-level elements, use COUNT_RECURSIVE to count nested elements.Do not use
count() on strings; use strlen() instead.Passing a non-array to
count() can give unexpected results.Remember to check if your variable is an array before counting to avoid confusion.