Friday, 08 Feb 2008 6:04PM EST

PHP: Multidimentional Arrays

PHP's associative arrays are very powerful in that they allow you to create arbitrary key values, rather than using the simple 0,1,2,3... that most programming languages force on you. For example, if you wanted to create a simple PHP array containing just 2 columns of information, an associative array would be perfect. Take the following 1 dimensional table of data about a pet:
Type Name Breed
Dog Lassie Collie

To represent this with an associative array:
$pets = array("Type"=>"Dog", "Name"=>"Lassie", "Breed"=>"Collie");
But what if you need to store the following table of data in an array?

Animal Name Breed
Dog Lassie Collie
Fish Nemo Clown Fish
Cat Garfield Orange Tabby

You could, of course, create 3 separate arrays; one for each animal. That method is very inefficient, though, and becomes impractical as the table grows. To creat a 2 dimensional array you simply create an array of arrays:
$pets = array( array("Type"=>"Dog", "Name"=>"Lassie", "Breed"=>"Collie"),
               array("Type"=>"Fish", "Name"=>"Nemo", "Breed"=>"Clown Fish"),
               array("Type"=>"Cat", "Name"=>"Garfield", "Breed"=>"Orange Tabby"),
             );
There are two different ways of accessing and displaying the data stored in a 2D array. The first is the manual (and sometimes painful) way:
echo "I have a ".$pets[0]["Type"]." named ".$pets[0]["Name"].". It is a ".$pets[0]["Breed"].".
"; echo "I have a ".$pets[1]["Type"]." named ".$pets[1]["Name"].". It is a ".$pets[1]["Breed"].".
"; echo "I have a ".$pets[2]["Type"]." named ".$pets[2]["Name"].". It is a ".$pets[2]["Breed"].".
";
The second way of accessing the data is to use a for loop (or nested for loops for a non-associative array):
for($i=0; $i<count($pets); $i++) {
  echo "I have a ".$pets[$i]["Type"]." named ".$pets[$i]["Name"].". It is a ".$pets[$i]["Breed"].".
"; }
If we needed to add some more data and further categorize the table, we could just as easily create a 3 dimensional array of data; in this case, organized by animal type:
$pets = array( array( array("Type"=>"Dog", "Name"=>"Lassie", "Breed"=>"Collie"),
                      array("Type"=>"Dog", "Name"=>"Pluto", "Breed"=>"Bloodhound"),
                    ),
               array( array("Type"=>"Fish", "Name"=>"Nemo", "Breed"=>"Clown Fish")
                    ),
               array( array("Type"=>"Cat", "Name"=>"Garfield", "Breed"=>"Orange Tabby"),
                      array("Type"=>"Cat", "Name"=>"Tom", "Breed"=>"Russian Blue")
                    ),
             );
And we could access and display this data with 3 nested for loops (or there's always the manual and painful way):
for($i=0; $i<count($pets); $i++) {
  for($j=0; $j<count($pets[$i]; $i++) {
    echo "I have a ".$pets[$i][$j]["Type"]." named ".$pets[$i][$j]["Name"].". It is a ".$pets[$i][$j]["Breed"].".
"; } }
And that's all you need to know to get started using multi-dimensional arrays in PHP. Of course, there are countless variations of this code and uses for it, so take the code, play with it and put it to good use. As always, if you have a technique that you think is better or a tweak that improves on this code, please share it in the comments. If you have a tip, a trick or an idea for my next post, please don't hesitate to contact me.
Bookmark and Share

0 Comments So Far

Post a comment


If you are seeing this message, you are either using a screen reader or you have disabled CSS. Please do not fill in the following form field, titled "lastname", or your comment will not be saved. This field is only used to help prevent spam comments.


Welcome

JustinSpegele.com is where I share projects that I'm working on, php tutorials, web development tips and tricks, and random thoughts.

#MLS has a very odd notion of an all-star game. MLS all-stars vs. an EPL team? Still, should be very fun to watch. MLS 3 - Man United 2 1:41 PM Jul 28th from web
The New Digg And The Future Of Social News http://bit.ly/cM7Guq 10:44 AM Jun 29th from TweetMeme
so as of right now, the Big 10 has 12 teams and the Big 12 has 10 teams? http://sports.espn.go.com/ncaa/news/story?id=5276668 7:59 PM Jun 11th from web
heading to Las Vegas for #caworld in the morning 7:12 PM May 12th from web
Found out from CNN that I went to high school with a convicted terrorist who worked with Al-Qaeda. Not what I expected to see on the news 9:49 PM May 10th from web
View all posts on Twitter »

Friend me

Twitter Digg Facebook FriendFeed Del.icio.us iFanboy Last.fm Squidoo

Login

Username:

Password: