Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 24 / 68

Two-Dimensional Arrays (Tabular Data)

In this lesson you will learn how to work with two-dimensional arrays in PHP so you can represent tables and grids. This is for anyone searching for "PHP 2D array how to use".

Putting arrays inside an array gives you a grid with rows and columns. This is called a two-dimensional array, and you access it with two indexes, as in $grid[row][column]. It is the basic idea behind game boards with coordinates and spreadsheet-like data.

The sample code builds a 2x3 $grid and reads the value at row 2, column 3 with $grid[1][2]. Notice how foreach ($grid as $row) takes each row and implode(",", $row) prints it readably.

A common stumbling block for beginners is swapping the row and column indexes. Writing $grid[column][row] reaches a completely different position. Deciding up front which index is which prevents the confusion.

You can also express three or more dimensions for more complex structures. Two-dimensional arrays turn up constantly in programs that handle grid-shaped data, such as image processing or managing a game board.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)