Php provides two functions for us to calculate the length of a one-dimensional array. For example, count and sizeof can both calculate the length of an array and obtain a two-dimensional array. The method for getting the array length in php is very simple. php provides two functions for us to calculate the length of one-dimensional arrays, such as count and sizeof, let's take a look at several instances.
How does php obtain the length of an array? Use the php function count () or sizeof ()
For example:
The Code is 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 array elements. we can get the number of elements in a regular scalar variable. If the array passed to this function is an empty array or an unspecified variable, the number of returned array elements is 0;
The two functions are the same. In the manual, sizeof () is the alias of the function count.
How can we calculate the length of a multi-dimensional array? Continue with the example
For example, the array you read is a two-dimensional array:
The Code is as follows:
$ 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, that is to say, the two-dimensional array has only two pieces of news, and the number you want is 2, but if you use different versions of php in count ($ arr, the statistical results are different;
Later, I found in the php manual that the count function has a second parameter, which is explained as follows:
The count function has two parameters:
0 (or COUNT_NORMAL) is the default value. Multi-dimensional arrays (arrays in the array) are not detected );
1 (or COUNT_RECURSIVE) is a multi-dimensional array for detection,
Therefore, if you want to determine whether the read array $ arr has news information, write the following statement:
The Code is as follows:
If (is_array ($ arr) & count ($ arr, COUNT_NORMAL)> 0)
{
.....
} Else {
.....
}
?>
You can use this code to test the function:
The Code is as follows:
$ Arr = array (
0 => array ('title' => 'news 1', 'viewnum' => 123, 'content' => 'zaqxswedcrfv '),
1 => array ('title' => 'news 2', 'viewnum' => 99, 'content' => 'qwertyuiopzxcvbnm ')
);
Echo 'multi-dimensional array not counted:'. count ($ arr, 0); // count ($ arr, COUNT_NORMAL)
Echo"
";
Echo 'multi-Dimensional Statistics array: '. count ($ arr, 1); // count ($ arr, COUNT_RECURSIVE)
?>