php method to get array length (with instance)

  • 2020-10-23 20:55:24
  • OfStack

In php, getting the length of an array is easy. php provides two functions to calculate the length of a 1-dimensional array. count and sizeof, for example, can count the length of an array directly.

How php gets the length of the array, using the php function count(), or sizeof()
Such as:


$arr = Array('0','1','2','3','4'); 
echo count($arr);
//  The output  5
$arr = array('A','B','C');
echo sizeof($arr);
// The output 3

sizeof() and count() serve the same purpose, both returning the number of elements in an array. You get the number of elements in a regular scalar variable. If the array passed to this function is an empty array or an undefined variable, the number of elements returned is 0.
sizeof() is the alias for the function count(), according to the manual.

So how do you count the length of a multidimensional array? Let's move on to the example
For example, the array you read is a 2-dimensional array:


<?php
$arr=array(
         0=>array('title' => ' news 1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
         1=>array('title' => ' news 2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
        );
?>

If you want to count the length of the array $arr, which means that the 2-dimensional array has only two news items, you also want the number 2, but if you use the count($arr) version of php, the result is different.
It was later discovered in the php manual that the count function has a second parameter, which is explained as follows:
The count function takes two arguments:
0(or COUNT_NORMAL) is the default, and multidimensional arrays (arrays within arrays) are not detected;
1(or COUNT_RECURSIVE) is to detect multidimensional arrays,
So if you want to determine if the read array $arr has news information, write this:


<?php
if(is_array($arr) && count($arr,COUNT_NORMAL)>0 )
{
 .....
} else {
 .....
}
?>

You can test the function by using code like this:


<?php
$arr=array(
         0=>array('title' => ' news 1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
         1=>array('title' => ' news 2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
        );

echo ' Do not count multidimensional arrays: '.count($arr,0);//count($arr,COUNT_NORMAL)
echo "<br/>";
echo ' Statistical multidimensional arrays: '.count($arr,1);//count($arr,COUNT_RECURSIVE)
?>

In the real world, we mostly use array ().length to get the length.


Related articles: