In PHP, there are many ways to declare a two-dimensional array and assign values to it. Several commonly used methods will be introduced below.
1. Assignment through key-value pairs
Key-value pairs mean that each element in the array has a key and a value, and the elements in the array can be accessed through the key.
Sample code:
$array = array( array('name' => 'Tom','age' => 23), array('name' => 'Jerry','age' => 25), );
At this time, $array is a two-dimensional array. Each element in an array is also an array, and each element has a name and age key.
2. Assignment through loops
You can easily assign values to two-dimensional arrays through loops. For example, you can use a for loop to define a two-dimensional array with 3 rows and 4 columns.
Sample code:
$array = array(); for($i = 0; $i < 3; $i++){ for($j = 0; $j < 4; $j++){ $array[$i][$j] = $i + $j; } } var_dump($array);
At this time, $array is a two-dimensional array with 3 rows and 4 columns. Each element in the array is a number.
3. Assignment through array functions
PHP provides some commonly used array functions, which can easily assign values to two-dimensional arrays. For example, you can use the array_fill() function to define a two-dimensional array with 5 rows and 5 columns.
Sample code:
$array = array_fill(0, 5, array_fill(0, 5, 'a')); var_dump($array);
At this time, $array is a two-dimensional array with 5 rows and 5 columns. Each element in the array is the string 'a'.
Summary:
The above are three common methods of assigning values to two-dimensional arrays. In actual development, there are many other methods, such as assigning values through files, databases, etc. But no matter which method, you can access and operate the elements in the array by traversing the array and calling functions. Careful developers can choose the appropriate method according to actual needs and optimize it based on their own experience to improve program operation efficiency and stability.
The above is the detailed content of How to assign value to two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!