You are on page 1of 4

Two-dimensional Arrays

In PHP, two-dimensional arrays are arrays that contain arrays. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. For example, a two-dimensional array called $rockBands could contain the names of the bands and some of the songs that they sing. Below is a grid that represents such a two-dimensional array.

rockBand Song1 Song2 Song3


Beatles Love Me Do Hey Jude Helter Skelter Rolling Stones Waiting on a Friend Angie Yesterday's Papers Eagles Life in the Fast Lane Hotel California Best of My Love

The following code creates this two-dimensional array. The internal arrays are highlighted. Note that the header row is not included.

Syntax
1 2 3 4 5 6 7 $rockBands = array( array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'), array('Rolling Stones','Waiting on a Friend','Angie', 'Yesterday\'s Papers'), array('Eagles','Life in the Fast Lane','Hotel California', 'Best of My Love') )

Reading from Twodimensional Arrays


To read an element from a two-dimensional array, you must first identify the index of the "row" and then identify the index of the "column." For example, the song "Angie" is in row 1, column 2, so it is identified as $rockBands[1][2]. Remember that the first row is row 0 and the first column is column 0.

Looping through Twodimensional Arrays


To loop through a two-dimensional array, you need to nest one loop inside of another. The following code will create an HTML table from our two-dimensional array.

Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 <table border="1"> <?php foreach($rockBands as $rockBand) { echo "<tr>";

foreach($rockBand as $item) { echo "<td>$item</td>"; } echo "</tr>"; } ?> </table> The above code snippets are combined in the following example to output a rockBands table.

You might also like