In PHP, you can use the count() function to judge. This function can get the length of the array. If you omit the second parameter, you will only get the number of elements in one dimension; therefore, you only need to compare the omitted parameters. When the parameters are not omitted, the length obtained is the same. The syntax is "count($arr)== count($arr,1)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In php, you can use count () function to judge.
<?php
header('content-type:text/html;charset=utf-8');
$array = array("php", 11, '', 12, "PHP中文网",13,"green",2021,"mysql","14",15);
if (count($array) == count($array, 1)) {
echo '是一维数组';
} else {
echo '是二维数组';
}
?>
Copy after login
Scheme principle:
##count ( mixed $var [, int $mode ] ) – Calculate the number of cells in the array or the number of attributes in the object
$mode: is an optional parameter and can be omitted.
- If the $mode parameter is omitted, or set to COUNT_NORMAL or 0, the count() function will not detect multidimensional arrays;
- If If $mode is set to COUNT_RECURSIVE or 1, the count() function will recursively count the number of elements in the array, which is especially useful for calculating the number of elements in multi-dimensional arrays.
If the $mode parameter is omitted, count will not detect multi-dimensional arrays and will only obtain the number of elements in one dimension.
So you only need to compare whether the obtained lengths are the same when the $mode parameter is omitted and when the $mode parameter is not omitted, you can determine whether it is a one-dimensional array or a two-dimensional array.
- $mode parameter example:
<?php
header("Content-type:text/html;charset=utf-8");
$arr= array
("张三",
25,
array("高数","PHP教程","英语"),
);
//输出语句
echo "数组长度为:".count($arr,1);
echo "<br>不递归检测数组,长度为:".count($arr);
?>
Copy after login
Output:
数组长度为:6
不递归检测数组,长度为:3
Copy after login
After reading the above output, it is Aren't you confused? There are only 5 elements in the array ("Zhang San", 25, "High Number", "PHP Tutorial", "English"). Why is the array length displayed in the result not 5, but 6?
In fact, this is because at this time, the count() function loops to count all elements in the two-dimensional array, and "array("高数","PHP tutorial","English")" will be regarded as an overall statistics Once, the elements in it ("Advanced Mathematics", "PHP Tutorial", "English") will be counted again, so the final result is 6.
Recommended: "
PHP Video Tutorial"
The above is the detailed content of How to determine whether a one-dimensional array or a two-dimensional array in PHP. For more information, please follow other related articles on the PHP Chinese website!