Multi-Dimensional Arrays
Multi-dimensional arrays are actually pretty simple. For each dimension of the array, you add another [key] value to the end:
$a[1] = $f; # one dimensional examples
$a["foo"] = $f;
$a[1][0] = $f; # two dimensional
$a["foo"][2] = $f; # (you can mix numeric and associative indices)
$a[3]["bar"] = $f; # (you can mix numeric and associative indices)
$a["foo"][4]["bar"][0] = $f; # four dimensional!
You can "fill up" multi-dimensional arrays in many ways, but the trickiest one to understand is how to use the array()
command for associative arrays. These two snippets of code fill up the one-dimensional array in the same way:
Example 1:
$a["color"] = "red";
$a["taste"] = "sweet";
$a["shape"] = "round";
$a["name"] = "apple";
$a[3] = 4;
Example 2:
$a = array(
"color" => "red",
"taste" => "sweet",
"shape" => "round",
"name" => "apple",
3 => 4
);
The array() function can be nested for multi-dimensional arrays:
<?
$a = array(
"apple" => array(
"color" => "red",
"taste" => "sweet",
"shape" => "round"
),
"orange" => array(
"color" => "orange",
"taste" => "sweet",
"shape" => "round"
),
"banana" => array(
"color" => "yellow",
"taste" => "paste-y",
"shape" => "banana-shaped"
)
);
echo $a["apple"]["taste"]; # will output "sweet"
?>