Often I get con­tact­ed by peo­ple regard­ing their frus­tra­tion in under­stand­ing how Mul­ti­di­men­sion­al Arrays work. This leaves me won­der­ing why is it that dif­fi­cult to under­stand Mul­ti­di­men­sion­al Arrays? Maybe the rea­son that peo­ple have a hard time under­stand­ing the whole Mul­ti­di­men­sion­al Array con­cept is because book authors don’t take the time to explain Arrays in easy-to-grasp man­ner.

In PHP, a Mul­ti­di­men­sion­al Array looks like this:

There, a very basic exam­ple of a mul­ti­di­men­sion­al array in PHP. And here’s how you out­put the val­ues stored in the “Blog” array:-

Just try view­ing the code in your brows­er and it looks some­thing like this:

Multi-dimentional Array Output

Look close­ly and you’ll find the last pair of “Prop­er­ty => Val­ue” doesn’t show what one might expect it to show. The rea­son is pret­ty sim­ple. The “Pages” key of our “Blog” array is not a nor­mal key. It’s an array inside an array. If you do a sim­ple “View Source” exer­cise, you’ll get some­thing like this:

22104521-multidArray_output_vs

This is where peo­ple tend to get con­fused. If you fol­low my advice, there is noth­ing to wor­ry about. Since we already know that the key “Pages” is an array, this is how we out­put val­ues stored in the “Pages” prop­er­ty:

The out­put looks like this:

22104598-multidArray_output_2

Here is a prac­ti­cal PHP exam­ple using an EXIF func­tion to out­put META infor­ma­tion stored in image head­ers:

The out­put:

exif array output

Now sup­pose if we only need­ed to cap­ture the fol­low­ing infor­ma­tion from this whole infor­ma­tion tree:

  • Name :
  • Make :
  • Mod­el :
  • Soft­ware :
  • Cap­ture Time :
  • Expo­sure Time :
  • ISO Speed :
  • Image Height :
  • Image Width :
  • CCD :

If you pay atten­tion, cap­tur­ing all the above infor­ma­tion is a pret­ty sim­ple process:

The out­put:

22104625-image-meta-output

As you can see, out­putting infor­ma­tion from a nest­ed array is just a mat­ter of fol­low­ing this sim­ple pat­tern: $array[‘nested-array’][‘nested-property’] Now, at this stage, some of you might be won­der­ing how can one print out all the “prop­er­ty” => “val­ue” pairs stored in a mul­ti­di­men­sion­al array! Here is how you can achieve this using the built-in is_array() func­tion:

The out­put:

22540154-Selection_009

Now try doing “View Source” and you’ll see nice­ly-tabbed HTML source code. When­ev­er I’m writ­ing code that sends out­put to the brows­er, I try to make sure it looks good even under the hood:

22540493-Selection_010

Tagged with →  
Share →
%d bloggers like this: