konte
Home page
 
 Home 
 ASP 
 PHP 
 SQL 
 HTML 
 JavaScript 
 Search 
 Contact 
 


Search
or browse popular tags
Subscription

Sign up for the free email newsletter for new tips, tutorials and more. Enter your email address below, and then click the button.

Privacy Policy

Syndicate

[XML] Latest Tutorials


Home / PHP

 

 
PHP: Multidimensional Arrays Print Email

Array does not have to be a simple list of keys and values; each array element can contain another array as a value, which in turn can hold other arrays as well. In such a way you can create two-dimensional or three-dimensional array.

Two-dimensional Arrays

Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles and prices. But if you need to keep more than one item of each type you need to use something different - one of the ways to do it is using multidimensional arrays. The table below might represent our two-dimensional array. Each row represents a type of flower and each column – a certain attribute.

Title Price Number
rose 1.25 15
daisy 0.75 25
orchid 1.15 7

To store data in form of array represented by preceding example using PHP, let’s prepare the following code:

<?php
$shop = array( array("rose", 1.25 , 15),
               array("daisy", 0.75 , 25),
               array("orchid", 1.15 , 7) 
             ); 
?>

This example shows that now $shop array, in fact, contains three arrays.  As you remember, to access data in one-dimensional array you have to point to array name and index. The same is true in regards to a two-dimensional array, with one exception: each element has two indexes – row and column.

To display elements of this array we could have organize manual access to each element or make it by putting For loop inside another For loop:

<?php
echo "<h1>Manual access to each element</h1>";

echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />";

echo "<h1>Using loops to display array elements</h1>";

echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    for ($col = 0; $col < 3; $col++)
    {
        echo "<li>".$shop[$row][$col]."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
?>

Perhaps, instead of the column numbers you prefer to create their names. For this purpose, you can use associative arrays.  The following code will store the same set of flowers using column names:

<?php
$shop = array( array( Title => "rose", 
                      Price => 1.25,
                      Number => 15 
                    ),
               array( Title => "daisy", 
                      Price => 0.75,
                      Number => 25,
                    ),
               array( Title => "orchid", 
                      Price => 1.15,
                      Number => 7 
                    )
             );
?>

It is easier to work with this array, in case you need to get a single value out of it. Necessary data can be easily found, if you turn to a proper cell using meaningful row and column names that bear logical content.  However, we are loosing the possibility to use simple for loop to view all columns consecutively.

You can view outer numerically indexed $shop array using the for loop. Each row of the $shop array is an associative array.  Hence, inside the for loop you need for each loop.  Also you can get each element from associative array manualy:

<?php
echo "<h1>Manual access to each element from associative array</h1>";

for ($row = 0; $row < 3; $row++)
{
    echo $shop[$row]["Title"]." costs ".$shop[$row]["Price"]." and you get ".$shop[$row]["Number"];
    echo "<br />";
}

echo "<h1>Using foreach loop to display elements</h1>";

echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    foreach($shop[$row] as $key => $value)
    {
        echo "<li>".$value."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
?>

Back to top

Three-dimensional Arrays

You don’t have to be limited by two dimensions: the same way as array elements can contain other arrays, these arrays, in their turn, can contain new arrays. 

Three-dimensional array is characterized by height, width, and depth. If you feel comfortable to imagine two-dimensional array as a table, then imagine a pile of such tables.  Each element can be referenced by its layer, row, and column.

If we classify flowers in our shop into categories, then we can keep data on them using three-dimensional array. We can see from the code below, that three-dimensional array is an array containing array of arrays:

<?php
$shop = array(array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7) 
                   ),
              array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7) 
                   ),
              array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7) 
                   )
             );
?>

As this array has only numeric indexes, we can use nested for loops to display it:

<?php
echo "<ul>";
for ( $layer = 0; $layer < 3; $layer++ )
{
    echo "<li>The layer number $layer";
    echo "<ul>";
   
    for ( $row = 0; $row < 3; $row++ )
    {
       echo "<li>The row number $row";
       echo "<ul>";
     
        for ( $col = 0; $col < 3; $col++ )
        {
            echo "<li>".$shop[$layer][$row][$col]."</li>";
        }
        echo "</ul>";
        echo "</li>";
    }
    echo "</ul>";
    echo "</li>";
}  
echo "</ul>";
?>

This way of creating multidimensional arrays allows to create four- and five-dimensional arrays. Syntax rules do not limit the number of dimensions, but the majority of practical tasks logically correspond to the constructions of three or less dimensions.

Back to top

Tags: PHP ARRAYS MULTIDIMENSIONAL KEY VALUE TWO-DIMENSIONAL THREE-DIMENSIONAL

Add To: Add to dzone dzone | Digg this digg | Add to del.icio.us del.icio.us | Stumble it stumbleupon


Hide Comments | Add New
Your tutorial has really been helpful!
I was looking at w3schools.com, but they merely touched this topic of multidimensional arrays, without even mentioning how to read from it. But your tutorial covers almost everything in depth.
Very nice work.
Thanks!
# Posted by sjku | 26 Dec 2006 02:06:23
It is not clear why we need so huge structure. Why we cannot create arrays like we do in perl?
# Posted by valery | 30 Mar 2007 05:48:15
Thanks so much for this great tutorial !

I been programming PHP for a while but always had problems with
two dimensionals arrays, you explained the topic very clearly !

Actually very easy but in the books, they make a big matter out of if !

Thanks
# Posted by Gunther von Goetzen | 6 Apr 2007 02:30:56
This is helpful. But what I need to know how to sort multi dimensional array. Like sorting them via highest prices and of the same time highest volume. If incase they have the same prices or same volume. : )
# Posted by dimar | 27 May 2007 22:21:50
In a very few words, you have explained very simply what others spend mountains of text trying to define and often fail to do adequately.
Arrays are very logical and not very difficult to master, and their true power is in the ability to be multidimensional. I've never understood why the majority of writers (many of them good ones) make this such a complicated subject for beginners.
# Posted by BuddyL | 30 May 2007 06:51:35
Could you expand on this and explain how you would insert an associative array that has already been populated into another associative array?
# Posted by Addison | 5 Jul 2007 23:49:07
very good, thanks! added on del.icio.us
# Posted by hamilton | 12 Sep 2007 09:25:15
Nice examples buddy thanks.
# Posted by anil | 18 Sep 2007 23:29:48
This tutorial is one of a kind, it is really useful.
I have one question though. How can I dynamically populate the two dimensional array with values from a table so that I can use the dynamically populated array in one function? Considering that I have close to a 1000 rows that need to be transferred to the array. The two dimensional array I want to use in the function is similar to the one in your example.
Thank you in advance
# Posted by Silva | 29 Sep 2007 03:45:24
Hello

Thanks for the tutorial

I am interested on how to access 3 Dimentional associative array. Numerical is easy.

Can you convert this

<?php
$shop = array(array(array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
),
array(array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
),
array(array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
)
);
?>

to associative array and display the results.

Thanks
# Posted by AjnabiZ | 28 Nov 2007 04:39:01
As a senior Programmer (C/C++, Java, VB, Perl, PhP, SQL, UML, etc.), I can say unequivicably that you "hit it RIGHT OUT OF THE PARK!". I HATE when you have to "mull" over thousands of words before the author of an article gets to the point (if they ever do!). Thank you, whoever you are!
# Posted by CC | 9 Feb 2008 06:17:18
Thanks for the crystal clear tut.. thank yooooou :)
# Posted by Amila | 11 Jun 2008 20:20:06




Copyright © 2005-2007             www.WebCheatSheet.com All Rights Reserved.