Home » Featured, Headline, PHP Tutorials, Tutorials

Setting Up A Multidimensional Array

14 March 2009 108 views No Comment


We learned out to set up an array, add to an array, but instead of showing how to display the array and or deleting entries in the array, we are going a step further and go into how complicated arrays can get by setting up a multidimensional array. Now Multidimensional Array’s are a enigma they are both easy and complicated, the easy part is connecting everything together and displaying the data, the complicated part is actually structuring Multidimensional Array’s. Because of the fact that you will be using 2 or more arrays and you have to set them up properly in order for the data to be displayed properly.

So the first part in this craziness is to set up the first array:

// Create the first array:
$phpvqs = array (1 => 'Getting Started', 'Variables', 'HTML Forms and PHP', 'Using Numbers');

Once you have an idea what your arrays will look like and what you want to have in them then the next one or two should be easy

// Create the second array:
$phpadv = array (1 => 'Advanced PHP Techniques', 'Developing Web Applications', 'Advanced Database Concepts', 'Security Techniques');
// Create the third array:
$phpmysql = array (1 => 'Introduction to PHP', 'Programming with PHP', 'Creating Dynamic Web Sites', 'Introduction to MySQL');

So in our three arrays we have keys $phpvqs, $phpadv, $phpmysql and of course their values. Now we must set up our Multidimensional Array using those three keys as our identifiers

// Create the multidimensional array:
$books = array (
'PHP VQS' => $phpvqs,
'PHP 5 Advanced VQP' => $phpadv,
'PHP 6 and MySQL 5 VQP' => $phpmysql
);

Now you will notice that we are using the keys from first array’s as values “strings” and that we are using completely new keys that will be used to identify the values (keys) from the first arrays and when it does they will be displayed like so

// Print out some values:
print "The third chapter of my first book is {$books['PHP VQS'][3]}.";
print "The first chapter of my second book is {$books['PHP 5 Advanced VQP'][1]}.";
print "The fourth chapter of my fourth book is {$books['PHP 6 and MySQL 5 VQP'][4]}.";

// See what happens with foreach:
foreach ($books as $key => $value) {
print "$key: $value n";
}

We are doing several things here first we are telling the second set of keys to run, but we are telling them to display a specific value from the first set of keys and so the following will be displayed HTML Forms and PHP, Advanced PHP Techniques, and Introduction to MySQL.

The part which is something that could have been covered is the actual display of the arrays, if you remember that arrays have a specific way of being display and I had shown one of those ways error the other is foreach function, which I would recommend checking up on.


Leave your response!

You must be logged in to post a comment.