Two-dimensional Arrays

Contact Us or call 1-877-932-8228
Two-dimensional Arrays

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

$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 Two-dimensional 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 Two-dimensional 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

<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.

Code Sample:

Arrays/Demos/TwoDimensionalArrays.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Two-dimensional Arrays</title>
</head>

<body>
<h1>Two-Dimensional Arrays</h1>
<?php
$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')
);
?>
<table border="1">
<tr>
	<th>rockBand</th>
	<th>Song 1</th>
	<th>Song 2</th>
	<th>Song 3</th>
</tr>
<?php
foreach($rockBands as $rockBand)
{
	echo '<tr>';
	foreach($rockBand as $item)
	{
		echo "<td>$item</td>";
	}
	echo '</tr>';
}
?>
</table>
</body>
</html>
Next