Home >Backend Development >PHP Problem >How to define a two-dimensional array with several rows and columns in PHP
In PHP, defining a two-dimensional array can be completed with a simple statement. The syntax is as follows:
$array = array( array(element1, element2, element3, ..., elementn), array(element1, element2, element3, ..., elementn), array(element1, element2, element3, ..., elementn), ... array(element1, element2, element3, ..., elementn) );
Among them, element
is each element in this two-dimensional array. The value can be a number, string, Boolean value, object, etc.
If you want to define a two-dimensional array with n rows and m columns, you can use a nested loop to achieve it:
$rows = n; // 行数 $cols = m; // 列数 $array = array(); // 定义一个空的二维数组 for ($i=0; $i<$rows; $i++) { $sub_array = array(); // 定义一个空的一维数组,作为二维数组中的每一行 for ($j=0; $j<$cols; $j++) { $sub_array[] = $element; // 将每一个元素的值赋值给一维数组 } $array[] = $sub_array; // 将一维数组添加到二维数组中 }
In the above code, we first define the rows of the two-dimensional array to be created number and column number, then use two nested loops to assign a value to each element, and finally add each one-dimensional array created to the two-dimensional array.
It is worth noting that in the above code, the value of the $element variable needs to be defined according to specific needs. If you want to define a two-dimensional array in which all elements are 0, you can define it as 0, as shown below:
$rows = n; // 行数 $cols = m; // 列数 $array = array(); // 定义一个空的二维数组 for ($i=0; $i<$rows; $i++) { $sub_array = array(); // 定义一个空的一维数组,作为二维数组中的每一行 for ($j=0; $j<$cols; $j++) { $sub_array[] = 0; // 将每一个元素的值赋值为0 } $array[] = $sub_array; // 将一维数组添加到二维数组中 }
In this way, you can get a $n\times m$ in which all elements are 0 A two-dimensional array.
In addition to the above method, you can also use PHP's array_fill() function to achieve assignment to a two-dimensional array, as shown below:
$rows = n; // 行数 $cols = m; // 列数 $element = 0; // 要填充的元素 $array = array_fill(0, $rows, array_fill(0, $cols, $element));
In the above code, we use the array_fill() function Let's first create a one-dimensional array, then use this function to create a two-dimensional array, and use the one-dimensional array as the initial value of each row, and finally get a two-dimensional array of $n\times m$.
The above is the detailed content of How to define a two-dimensional array with several rows and columns in PHP. For more information, please follow other related articles on the PHP Chinese website!