How to Find Length of Array in PHP: Simple Guide
In PHP, you can find the length of an array using the
count() function. It returns the number of elements in the array as an integer.Syntax
The basic syntax to find the length of an array is:
count(array, mode)- array: The array you want to count elements of.
- mode (optional): Use
COUNT_NORMAL(default) to count only top-level elements, orCOUNT_RECURSIVEto count elements recursively in multi-dimensional arrays.
php
count(array $array, int $mode = COUNT_NORMAL): int
Example
This example shows how to use count() to get the number of elements in a simple array.
php
<?php $fruits = ['apple', 'banana', 'cherry']; $length = count($fruits); echo "The array has $length elements."; ?>
Output
The array has 3 elements.
Common Pitfalls
One common mistake is trying to use sizeof() thinking it is different, but it is actually an alias of count(). Another pitfall is forgetting that count() only counts top-level elements unless you use the recursive mode.
Also, passing a non-array variable to count() will return 1 for non-empty scalars, which can be confusing.
php
<?php // Wrong: expecting count of nested elements without recursive mode $nested = [1, 2, [3, 4]]; echo count($nested); // Outputs 3, not 4 // Right: use recursive mode to count all elements echo count($nested, COUNT_RECURSIVE); // Outputs 5 // Wrong: passing a string $notArray = "hello"; echo count($notArray); // Outputs 1, not 0 or error ?>
Output
3
5
1
Quick Reference
Here is a quick summary of the count() function usage:
| Function Call | Description | Output Example |
|---|---|---|
| count($array) | Counts top-level elements in array | 3 |
| count($array, COUNT_RECURSIVE) | Counts all elements recursively | 5 |
| sizeof($array) | Alias of count() | 3 |
| count($string) | Returns 1 for non-empty scalar | 1 |
Key Takeaways
Use the count() function to get the number of elements in an array.
count() counts only top-level elements by default; use COUNT_RECURSIVE to count nested elements.
sizeof() is an alias of count() and works the same way.
Passing non-array variables to count() can give unexpected results.
Always check your data type before using count() to avoid confusion.