Multi-Dimensional Arrays

Creating multi-dimensional arrays in PHP is very similar to creating multi-dimensional arrays in C/C++. In C/C++ you have support for single-dimension arrays, but you create a multi-dimensional array by nesting an array as an element in a parent array. This is exactly how you create multi-dimensional arrays in PHP. You make an array that holds an array.

<?php
$board = array(“Row1” => array(“a”, “b”), “Row2” => array(“c”, “d”, “e”));
echo($board[“Row1”][0]);    // Prints “a”
echo($board[“Row2”][2]);    // Prints “e”
?>

One great use for multi-dimensional arrays is that you can represent a game board using a two-dimensional array. Then each position in the game board, at say location e1, would hold a value that would tell you if there is a piece at that square or not. Or you could use a loop, like in the following example, to print the game board:

<?php
$board = array(array(“r”, “k”, “b”, “q”, “k”, “b”, “k”, “r”),
array(“p”, “p”, “p”, “p”, “p”, “p”, “p”, “p”),
array(“&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”,
    “&nbsp;”, “&nbsp;”, “&nbsp;”),
array(“&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”,
    “&nbsp;”, “&nbsp;”, “&nbsp;”),
array(“&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”,
    “&nbsp;”, “&nbsp;”, “&nbsp;”),
array(“&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”,
    “&nbsp;”, “&nbsp;”, “&nbsp;”),
array(“p”, “p”, “p”, “p”, “p”, “p”, “p”, “p”),
array(“r”, “k”, “b”, “q”, “k”, “b”, “k”, “r”));

echo(“<table border=1 cellpadding=2 cellspacing=0 width=250>”);
for($yIndex = 0; $yIndex < count($board); $yIndex++)
{
    echo(“<tr>”);
        for($xIndex = 0; $xIndex < count($board[$yIndex]); $xIndex++)
    {
        echo(“<td align=center valign=middle>“ .
            $board[$yIndex][$xIndex] . ”</td>”);
    }
    echo(“</tr>”);
}
echo(“</table>”);
?>

The results of this loop look like Figure 6.5.

Figure 6.5. Results of looping through a multi-dimensional array.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset