PHP array length
In this post, you will learn how to calculate the PHP array length. In the development process, we may come to the situation where we need to count the total number of elements or values in an array. We can easily get this by using PHP predefined functions 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.
PHP get array length using 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. The COUNT_NORMAL mode does not count all elements of multidimensional arrays and COUNT_RECURSIVE counts the array recursively.
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
PHP get array length using sizeof() function
The sizeof() function returns the number of elements in an array. It is the 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 using 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
PHP pass array in URL query stringPHP 7 Arrays with operations
PHP convert associative array to XML
PHP loop through an associative array
PHP convert string into an array
PHP remove element from array by value
PHP in_array() function
PHP array_unshift() function
Simple PHP File Cache
How to get current directory, filename and code line number in PHP
Import Excel File into MySQL using PHP
JavaScript display PDF in the browser using Ajax call
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP