In PHP, we often need to operate on arrays, including determining whether the array is a multi-dimensional array. The so-called multi-dimensional array is an array with one or more layers nested in the array. For PHP developers, determining whether an array is a multi-dimensional array is a basic operation. Let’s introduce it in detail below.
1. What is an array?
In PHP, array is a very common data structure, which is used to store a set of data. PHP arrays can contain any type of data, including integers, floating point numbers, strings, objects, etc. In PHP, arrays can be defined in the following two ways:
Use the array() function to create an array, for example:
$fruits = array('apple', 'banana', 'orange');
Use square brackets [] to create an array, for example:
$fruits = ['apple', 'banana', 'orange'];
2. What is a multidimensional array?
A multidimensional array is an array with one or more layers nested within the array. For example:
$students = [ [ 'name' => '张三', 'age' => 18, 'sex' => '男' ], [ 'name' => '李四', 'age' => 19, 'sex' => '女' ] ];
In the above example, $students is a two-dimensional array, which contains two elements, each element is an array containing three key-value pairs.
3. How to determine whether an array is a multi-dimensional array?
There are many ways to determine whether an array is a multidimensional array. Here are some common methods.
PHP provides an array_depth() function, which can be used to obtain the depth of the array, which is the number of dimensions of the array. If an array is multidimensional, its depth will be greater than 1.
For example, we can use the array_depth() function to determine whether $students is a multi-dimensional array:
$students = [ [ 'name' => '张三', 'age' => 18, 'sex' => '男' ], [ 'name' => '李四', 'age' => 19, 'sex' => '女' ] ]; $depth = array_depth($students); if ($depth > 1) { echo '是多维数组'; } else { echo '不是多维数组'; }
The above code will output "It is a multi-dimensional array".
function is_multi_array($arr) { foreach ($arr as $val) { if (is_array($val)) { return true; } } return false; } $students = [ [ 'name' => '张三', 'age' => 18, 'sex' => '男' ], [ 'name' => '李四', 'age' => 19, 'sex' => '女' ] ]; if (is_multi_array($students)) { echo '是多维数组'; } else { echo '不是多维数组'; }
The above is the detailed content of PHP determines whether an array is multidimensional. For more information, please follow other related articles on the PHP Chinese website!