Introduction to PHP – Getting to Know Arrays Part 4

Guest Posts Paolo Nikko Nuñal

The last part of our tutorial with arrays will tackle on Multidimensional Arrays. Although pretty much the same as associative arrays in which it involves with "keys", however  this time around it will be dealing with an array within an array.

<?php 
    $myArray = array(
    array ("Smith","Aaron Smith","James Smith"),
    array ("Anderson","Harold Anderson","Carla Anderson"),
    array ("Baggins","Froddo Baggins","Bilbo Baggins")
    );

  echo myArray[0][0]; // RETURNS "Smith"
  echo myArray[0][1]; // RETURNS "Aaron Smith"
  echo myArray[2][1]; // RETURNS "Froddo Baggins"
?>


Based from the example above you can cycle through an array through its index.  The first index in the array is the "Smith" in which it is located at index [0][0]. The next one is "Aaron Smith" which is located at [0][1] and so on.

The next one we will be dealing with is Multidimensional Arrays that contains keys. In a multidimensional array, each element in the array can be an array and each element can be considered as a sub-array.

<?php 
    $myArray = array(
       "Smith"=>array
        (
          "Aaron","James","Finch"
        ),
       "Anderson"=>array
        (
           "Harold","Carla",Jonan"
        ),
       "Baggins"=>
        (
           "Froddo","Bilbo","Gron"
        )
);


The code above will be pretty much the same as associative arrays in which you use keys to access a specific element in the array and return the value. This time around you will be able to call the key and return what's inside the key according to their index. Think of it as an array within an array.

For example if you want to display the string "Bilbo" you need to call the key in which it is associated with "Baggins". To do this all you have to do is call the array name which is $myArray followed by the "key" and index". Since Baggins is located in index[1] we call it by $myArray['Baggins'][1]. for Jonan we can call it using $myArray['Anderson'][2];