PHP array length
Sometimes, we want to know the total number of elements in an array during development. We can easily get this by using PHP predefined function count() and sizeof(). These functions are used to get the number of elements or values in an array. Here, we explain how to use these functions.
count() function
The count() function returns the number of elements in an array.
Syntaxcount(array, mode)
Here, array specifies the array variable which is required to calculate the PHP array length and the second argument is optional which specifies the mode, possible value is either 0 or 1. The 0 and 1 represents COUNT_NORMAL and COUNT_RECURSIVE. If no value passed as the second argument, then the default value is COUNT_NORMAL.
Example<?php
$arr = array('k1'=>array('Book', 'Pen', 'Copy'),
'k2'=> array('Table', 'Chair'));
echo "Array count: ". count($arr);
echo "<br/>";
echo "Array count recursive: ". count($arr, 1);
?>
Output
Array count: 2
Array count recursive: 7
sizeof() function
The sizeof() function returns the number of elements in an array. It is same as the count() function and accepts the same arguments as count().
Syntaxsizeof(array, mode);
Example
<?php
$arr = array('k1'=>array('Book', 'Pen', 'Copy'),
'k2'=> array('Table', 'Chair'));
echo "Array count: ". sizeof($arr);
?>
Output
Array count: 2
It is always recommended to use the count() method rather than sizeof(). As, there is no assurance for the alias name that they will exist or not in the future upgrade.
Related Articles
How to display PDF file in PHP from databaseHow to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP