In this PHP tutorial, you shall learn to find the array length, the number of elements in one-dimensional or multi-dimensional arrays, using count() function, with examples.
PHP Array Length
To find the length of an array in PHP, use count() function. The count() function takes array as an argument, finds and returns the number of elements in the array.
Syntax of count()
The syntax of count() function to find array length is
count ( $arr [, int $mode = COUNT_NORMAL ] )
where
| Parameter | Description |
| array | Required. Specifies the array |
| mode | Optional. Specifies the mode. Possible values: |
Function Return Value
count() function returns an integer representing number of elements in the array.
You will mostly use the following form of count() function.
count ( $arr )
We can store the returned value in a variable as shown below.
$length = count ( $arr )
If you pass multidimensional array, count($arr) returns length of array only in the first dimension.
If you want to count all elements in a multidimensional array recursively, pass COUNT_RECURSIVE as second argument, as shown in the following code sample.
count ( $arr, COUNT_RECURSIVE )
We will look into examples for each of these scenarios.
Examples
1. Find length of Indexed Array
This is a simple example to demonstrate the usage of count() function with array.
In the following program, we are initializing a PHP array with three numbers as elements. Then we are using count() function to find the number of elements in the array.
PHP Program
<?php
$arr = array( 41, 87, 66 );
echo count($arr);
?>
Output
