Getting array lengths in PHP is simple, PHP provides us with two functions to calculate the length of a one-dimensional array, such as count,sizeof can directly count the length of the array Oh, let's take a look at some examples here.
How PHP Gets the length of the array, using the PHP function count (), or sizeof ()
For example:
Copy Code code as follows:
$arr = Array (' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ');
echo count ($arr);
Output 5
$arr = Array (' A ', ' B ', ' C ');
echo sizeof ($arr);
Output 3
sizeof () and count () have the same purpose, both functions can return the number of elements in an array. You can get the number of elements in a regular scalar quantity, if the array passed to the function is an empty array, or a variable that is not set, the number of elements returned is 0 ;
two function functions, the manual says that sizeof () is an alias to the function count ().
So how to count the multidimensional array length? Continue to see the example
like the array you read is a two-dimensional array:
Copy Code code as follows:
<?php
$arr =array (
0=>array (' title ' => ' News 1 ', ' Viewnum ' => 123, ' content ' => ' ZAQXSWEDCRFV '),
1=>array (' title ' => ' News 2 ', ' Viewnum ' =>, ' content ' => ' qwertyuiopzxcvbnm ')
);
?>
if you want to count the length of the array $arr, which means that the two-dimensional array is only two news, the number you want is 2, but if you use the different versions of PHP with Count ($arr), the results are not the same;
later found in the PHP manual that the Count function also had a second argument, as explained below:
The
count function has two parameters:
0 (or count_normal) is the default and does not detect multidimensional arrays (arrays in an array);
1 (or count_recursive) for detecting multidimensional arrays,
so if you want to determine whether the read array $arr have news information, you should write this:
Copy Code code as follows:
<?php
if (Is_array ($arr) && count ($arr, count_normal) >0)
{
.....
} else {
.....
}
?>
You can use this code to test the function:
Copy Code code as follows:
<?php
$arr =array (
0=>array (' title ' => ' News 1 ', ' Viewnum ' => 123, ' content ' => ' ZAQXSWEDCRFV '),
1=>array (' title ' => ' News 2 ', ' Viewnum ' =>, ' content ' => ' qwertyuiopzxcvbnm ')
);
Echo ' does not count multidimensional arrays: '. Count ($arr, 0);//count ($arr, Count_normal)
echo "<br/>";
Echo ' statistical multidimensional array: '. Count ($arr, 1);//count ($arr, count_recursive)
?>