PHP Multidimensional Arrays
A multidimensional array is an array that holds other arrays as its values. The inner arrays work like rows in a grid.
Reading one cell with two indexes
The grid holds two rows of two numbers. The indexes 1 and 0 pick the first value of the second row.
<?php
$grid = [[1, 2], [3, 4]];
echo $grid[1][0] . "\n";Printing the whole grid
print_r shows each row as an Array block inside the outer block.
<?php
$grid = [[1, 2], [3, 4]];
print_r($grid);Printing each row with nested loops
The outer foreach takes one row at a time. The inner foreach prints the values of that row on one line.
<?php
$grid = [[1, 2], [3, 4]];
foreach ($grid as $row) {
foreach ($row as $cell) {
echo $cell . " ";
}
echo "\n";
}Example
<?php
$seats = [["free", "taken"], ["taken", "free"]];
echo $seats[0][1] . "\n";
foreach ($seats as $row) {
foreach ($row as $seat) {
echo $seat . " ";
}
echo "\n";
}Key points
- A multidimensional array is a grid built from arrays inside one array.
- Each inner array is one row of the outer array.
- The first index picks the row.
- The second index picks the value in that row.
- Indexes start at 0 for the rows and for the values in each row.
- A foreach loop can visit each row, and a second foreach visits the values in that row.
In this example, the seats grid holds two rows of seat states. The first line reads row 0 at place 1, and that cell holds the word taken. The nested loops then print each row on its own line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
The grid is $grid = [[1, 2], [3, 4]]. What does $grid[0][1] hold?