> > How to strucutre arrays and multidimensional arrays in php

How to strucutre arrays and multidimensional arrays in php

Posted on Sunday 12 August 2012 | No Comments

Arrays with two or three indexes with values are easy to build. But when it comes to make a multidimensional array, if not structured properly, you’ll confuse what values correspond to what index.

However, if you make such arrays in a proper structure, then even a php beginner knowing arrays would understand it easily.

The proper structuring plays a big role in making complex programs to help avoid confusion in understanding the code and the code looks great too.

See this example of a single array having many indexes, the confusing structure and the proper structure.

The confusing one -
<?php

$something = array ( 'name' => 'Mike Todd', 'phone' => '010010001', 'city'= > 'A city', 'country' => 'America', 'job' => 'GainInfoTech Inc.');

?>

This may be a bit confusing as compared to the structure of the array you’ll see next. You can see all the indexes and values lie on one line and can be understood easily.

 The Proper Structure -
<?php

$something = array (
              'name' => 'Mike Todd',
              'phone' => '010010001',
              'city' => 'A city',
              'country' => 'America',
              'job' => 'GainInfoTech Inc.'
                    );

?>

Now, looking at this structure, at the first instant, you can tell what is the value corresponding to what index, isn’t it easy ? Of course it is.

Same structure should be applied when you are making a multidimensional array. See the quick example, and understand the structure.

<?php

$something = array (
             'value1' => array(
                         'value1.1' => 'some_value1.1.1',
                         'value1.2'=> 'some_value1.2.2',
                         'value1.3' => 'some_value1.3.3'
                               ),
              'value2' => array(
                          'value2.1' => 'some_value2.1.1',
                          'value2.2' => 'some_value2.2.2'
                                )
                    );

?>

To get rid of confusion, take a look at the corresponding values of indexes of this array, then you’ll understand easily.

$something['value1']['value1.1'] // has value some_value1.1

$something['value1']['value1.2'] // has value some_value1.2

$something['value1']['value1.3'] // has value some_value1.3

$something['value2']['value2.1'] // has value some_value2.1

$something['value2']['value2.2'] // has value some_value2.2

Note where the commas are placed. This is the main confusing part as of the versions of PHP below the 5.4.5. You can not put the comma after the last index value of the array as PHP versions below 5.4.5 do not support it but the version 5.4.5 (latest) and above (any further) do.

So this was a simple post telling you about a bit of what is the best way of structuring arrays.

Leave a Reply

Powered by Blogger.