PHP Array is a commonly used data structure type, that is used to store values of any type. PHP allows storing different types of data in an PHP array. Each element in a PHP Array can be accessed via its index number. While writing logics, the PHP Array Length needs to be calculated for various purposes.
PHP allows using two functions for calculating PHP array length i.e., count() and sizeof(). There is absolutely no difference in these two functions, both will return the PHP array length. However, the recommended approach is to use count() more often for PHP array length, since sizeof() can create an illusion to some programmers of returning size in bytes or something which is not true.
HOW TO INITIALIZE AN ARRAY IN PHP? Learn below
Table of Contents
PHP count( ) to Calculate Array Length
- Create a .php file, and save it in C: > xampp > htdocs.
- Start Apache server for xampp control panel.
Let’s start coding.
<?php
//Demonstration of count()
$myarr = array('apple', 'mango', 'banana', 'peach');
$arrLen = count($myarr);
echo("Array Length calculated with Count(): ".$arrLen);
?>
Here,
- array() is a built-in PHP method to define an array.
- echo() is again a built-in PHP method which is used to print the output on browser window.
- count() as discussed, will return the length of array.
Output

PHP sizeof( ) to Calculate Array Length
The second approach to calculate PHP array length is to use sizeof() method on the array. See the example below.
<?php
//Demonstration of sizeof()
$myarr = array('apple', 'mango', 'banana', 'peach');
$arrLen = sizeof($myarr);
echo("Array Length calculated with sizeof(): ".$arrLen);
?>
Output

PHP Multidimensional Array Length
<?php
//Multidimensional Array
$MDArray = array(
1,
2,
3,
4,
5,
array(
10,
20,
30
)
);
echo("Array Length calculated with Count(): ". count($MDArray, COUNT_RECURSIVE));
echo("<br/><br/>");
echo("Array Length calculated with sizeof(): ". sizeof($MDArray, COUNT_RECURSIVE));
echo("<br/><br/>");
echo("Multidimensional Array Length without using COUNT_RECURSIVE: ". count($MDArray));
?>
PHP COUNT_RECURSIVE
PHP count_recursive is used to tell the function to recursively dive into the array structure and count each entry, thus the methods will count all the elements of the array and the elements inside the array of an array. Without COUNT_RECURSIVE the methods will not count the elements of array that is inside the array.
Output

Conclusion
In this article, we discussed about the ways to calculate length of array in PHP. We practically observed two methods i.e., count() and sizeof() doing the same job, and later we finally implemented them on multidimensional arrays. We also observed what difference COUNT_RECURSIVE can make in determining the length of multidimensional arrays.