Categories
Learning Journal

Create Multidimensional PHP Arrays

Creating a multidimensional array is quite simple as long as you get over the initial confusion learning to create or work with one.

Quite simply, a multidimensional array is also an array except that it can hold other arrays as a value (in the regular key=>value pair of an array), which in turn can hold other arrays as well!

If that sentence didn’t confuse you, you probably do not need to read further…

So, you didn’t get it yet.

A possible multidimensional array structure

A regular, numerically indexed or associative array, may look something like this:

// Numerically Indexed Array
$songs = array(
 'Impossible',
 'Beautiful',
 'Dirrty'
 );

// Associative Array
$album = array(
 'Christina'=>'Stripped',
 'Pink'=>'Missundaztood',
 'Kelly'=>'Simply Deep'
 );

A multidimensional array however, will contain another array as a possible value, something like our example below.

<?php
// Multidimensional Array
$cds = array(
 'Christina Aguilera'=>array(
 'Impossible',
 'Beautiful',
 'Dirrty'
 ),
 'Pink'=>array(
 'Just like a pill',
 'Family potrait',
 'Missundaztood'
 ),
 'Kelly Rowland'=>array(
 'Stole',
 'Obsession',
 'Past 12'
 )
);
// $cds is multidimensional array which is actually:
/*
- 3 numerically indexed VALUES containing
- an associative array for singer and songs
 in each and
- the list of song titles for each singer
 (in a numerically indexed array!).
*/
?>

You could even build your array like this using data off a text file or database to process later on in your script using foreach() and for() loops.

Sample code to output a multidimensional array onto a web page

Unless you have very good reasons, always use foreach() to process arrays; here’s an example script to present the sample array $cds above, in a web page:

<?php

// $cds = paste sample data above, here;

echo '<p><b>How many CDs in our collection?</b><br />
There are '.sizeof($cds)." CDs in our collection.</p>\n";

echo "<ol>\n";
foreach( $cds as $singer=>$songs )
{
 echo ' <li><b>'.$singer."</b>.<br />\n";
 echo " <em>Songs</em>: </li>\n";
 echo " <ul>\n";
 asort( $songs ); // sorts the list of songs
 foreach( $songs as $song )
 {
 echo ' <li>'.$song.".</li>\n";
 }
 echo " </ul>\n";
}
echo "</ol>\n";

?>

Questions? Ask them at our PHP forum.

Leave a Reply

Your email address will not be published. Required fields are marked *