Often I get contacted by people regarding their frustration in understanding how Multidimensional Arrays work. This leaves me wondering why is it that difficult to understand Multidimensional Arrays? Maybe the reason that people have a hard time understanding the whole Multidimensional Array concept is because book authors don’t take the time to explain Arrays in easy-to-grasp manner.

In PHP, a Multidimensional Array looks like this:

There, a very basic example of a multidimensional array in PHP. And here’s how you output the values stored in the “Blog” array:-

Just try viewing the code in your browser and it looks something like this:

Multi-dimentional Array Output

Look closely and you’ll find the last pair of “Property => Value” doesn’t show what one might expect it to show. The reason is pretty simple. The “Pages” key of our “Blog” array is not a normal key. It’s an array inside an array. If you do a simple “View Source” exercise, you’ll get something like this:


This is where people tend to get confused. If you follow my advice, there is nothing to worry about. Since we already know that the key “Pages” is an array, this is how we output values stored in the “Pages” property:

The output looks like this:


Here is a practical PHP example using an EXIF function to output META information stored in image headers:

The output:

exif array output

Now suppose if we only needed to capture the following information from this whole information tree:

  • Name :
  • Make :
  • Model :
  • Software :
  • Capture Time :
  • Exposure Time :
  • ISO Speed :
  • Image Height :
  • Image Width :
  • CCD :

If you pay attention, capturing all the above information is a pretty simple process:

The output:


As you can see, outputting information from a nested array is just a matter of following this simple pattern: $array[‘nested-array’][‘nested-property’] Now, at this stage, some of you might be wondering how can one print out all the “property” => “value” pairs stored in a multidimensional array! Here is how you can achieve this using the built-in is_array() function:

The output:


Now try doing “View Source” and you’ll see nicely-tabbed HTML source code. Whenever I’m writing code that sends output to the browser, I try to make sure it looks good even under the hood:


Tagged with →  
Share →
%d bloggers like this: