Wednesday, 14 May 2014

Multidimensional Arrays

Earlier in this tutorial, we have described arrays that are a single list of key/value pairs.
However, sometimes you want to store values with more than one key.
This can be stored in multidimensional arrays.
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and colum
We can store the data from the table above in a two-dimensional array, like this:
$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );


We can also put a For loop inside another For loop to get the elements of the $cars array (we still have to point to the two indices):

Example

<?php
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
  }
  echo "</ul>";
}
?>

No comments:

Post a Comment