Home > Article > Backend Development > What is the difference between php sizeof and count
php There is no difference between sizeof() and count(). The sizeof() function is an alias of the count() function, which means that the function and usage of the sizeof() function are exactly the same as the count() function, and both can be used to calculate the length of an array.
The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer
The method to obtain the array length in PHP is very simple. PHP provides us with two functions to calculate the length of an array, namely the count() and sizeof() functions.
But in fact, there is no difference between the count() and sizeof() functions. The sizeof() function is an alias of the count() function. The functions and usage of these two functions are exactly the same.
Grammar format:
count($array,$mode); sizeof($array,$mode);
Parameter description is as follows:
Tip: If $array is neither an array nor an object, return 1; if $array is equal to NULL, return 0.
Example 1: Use count() to count the number of array elements.
<?php header("Content-type:text/html;charset=utf-8"); $arr = ['PHP中文网','PHP教程','//m.sbmmt.com/','count()函数','sizeof()函数','数组长度']; echo '$arr 的长度为:'.count($arr).'<br>'; $arr2 = ['C语言中文网','PHP教程',['//m.sbmmt.com/','count()函数','sizeof()函数','数组长度']]; echo '$arr2 的长度为:'.count($arr2).'<br>'; echo '参数 $mode = 1 时,$arr2 的长度为:'.count($arr2, 1).'<br>'; $str = '//m.sbmmt.com/'; echo '$str 的长度为:'.count($str).'<br>'; ?>
Output result:
Example 2: Use sizeof() to count the number of array elements
<?php header("Content-type:text/html;charset=utf-8"); $arr = ['PHP中文网','PHP教程','//m.sbmmt.com/','count()函数','sizeof()函数','数组长度']; echo '$arr 的长度为:'.sizeof($arr).'<br>'; $arr2 = ['C语言中文网','PHP教程',['//m.sbmmt.com/','count()函数','sizeof()函数','数组长度']]; echo '$arr2 的长度为:'.sizeof($arr2).'<br>'; echo '参数 $mode = 1 时,$arr2 的长度为:'.count($arr2, 1).'<br>'; $str = '//m.sbmmt.com/'; echo '$str 的长度为:'.sizeof($str).'<br>'; ?>
Output result :
It can be seen that the results returned by using count() and sizeof() are the same.
Note: Line 7 of the code sets $mode to 1, and the count() and sizeof() functions will cycle through all elements in the two-dimensional array. At this time ['https://www .php.cn/','count() function','sizeof() function','array length']
will be counted once as a whole, and the elements in it will be counted once, so the final result is 7.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What is the difference between php sizeof and count. For more information, please follow other related articles on the PHP Chinese website!