Arrays and PHP: A Primer - Multi-dimensional arrays
(Page 5 of 6 )
If you're just new to arrays, then chances are multi-dimensional arrays will be a bit hard to grasp. However, once you've worked your way through this page, they shouldn't seem that difficult anymore.
Multi-dimensional arrays are simply arrays that can contain another "dimension" of indexes. For example, instead of creating a singly indexed array, we could add another column of indexes, like this:
<?php
$Arthur[1][1];
$Arthur[0][0] = "Index at 0,0";
$Arthur[0][1] = "Index at 0,1";
$Arthur[1][0] = "Index at 1,0";
$Arthur[1][1] = "Index at 1,1";
?>Our multi-dimensional array would be represented in our computers memory like this:

A good example of using a multi-dimensional array is to store the details of several different people. In one index, we could store the person's name. In another, their age, and in another their phone number. We could then display their details in a loop, like this:
<?
$People[0][1] = "John Doe";
$People[0][2] = 20;
$People[0][3] = "555-1465";
$People[1][1] = "Mary Moo";
$People[1][2] = 25;
$People[1][3] = "555-9007";
for($i = 0; $i < 2; $i++)
{
for($j = 0; $j < 4; $j++)
print $People[$i][$j] . "<br>";
}
?>Once again, our browser output would look like this:

Let me explain the details of our new code. Firstly, we are creating a new two-dimensional array. We could create a three or even four-dimensional array if we liked.
Next, we set the values of each index in the array. The left index starts from 0 and goes until 1. The right index starts from 1 and goes to 3. Lastly, we use two for loops (one inside another) to access each element in the array. The first loop traverses through the left index, while the inner loop traverses through (and displays) the right index.
We can also create a multi-dimensional array using the array function you saw earlier. To create a two-dimensional array, we could use some code like this:
<?php
$action = array(
1 => array(
1 => "Yes"
)
);
print $action[1][1];
?>After this, the value of $action[1][1] would be equal to "Yes". You should experiment with arrays in PHP to become more familiar with them.
Next: Conclusion >>
More PHP Articles
More By Tuna Celik