Re: Two dimensional arrays in PHP

From: Date: Thu, 22 Jun 2000 02:14:18 +0000
Subject: Re: Two dimensional arrays in PHP
References: 1  Groups: php.windows 
Request: Send a blank email to php-windows+get-573@lists.php.net to get a copy of this message
At 10:48 PM 6/21/00 -0300, Nasir Ali wrote:
Hi guys, I need help with PHP coding. Could someone tell me how to create, traverse, add values and insert values in a two dimensional array. Little code would be helpfull. I want to create this two dimensional array on the fly so the both dimensions are unknown, means I'll have to use variable to define both dimensions unless there is some other way out.
Hi Nasir, Arrays are very flexible in PHP. Here are a series of notes and examples on how to create all sorts of multi-dimensional arrays. 1.) Arrays do not need to be predefined. This is perfectly valid:
        $list = array ('one', 'two');
no clunky typing statements like:
        array $list[2];
        $list[0] = 'one';
        $list[1] = 'two';
are needed. 2.) Arrays can be assigned in many ways. Here are four different ways to create the same single-dimension array. $list = array ('one'); $list[] = 'one'; $list[0] = 'one'; $list = explode ('||', 'one'); 3.) Multi-dimensional arrays are easy to create. Here is one way to assign a 2x2 2-dimensional array: $array[0][0] = 'one-one'; $array[0][1] = 'one-two'; $array[1][0] = 'two-one'; $array[1][1] = 'two-two'; Here is another way to assign a 2x2 2-dimensional array: $list = array (
        array ('one-one', 'one-two'),
        array ('two-one', 'two-two'),
) 4.) Multi-dimensional arrays do not need to be balanced. An array that looks like this is perfectly valid: $list[0][0][0] = "one-one-one";
$list[1]       = "two";
5.) Traversing 2d arrays is also simple. If your 2d array looks like this: $array[0][0] = 'one-one'; $array[0][1] = 'one-two'; $array[1][0] = 'two-one'; $array[1][1] = 'two-two'; Then you can traverse it this way: for ($x=0; $x < count ($array); ++$x)
        for ($y=0; $y < count ($array[$x]); ++$y)
                print "\$array[$x][$y] = '".$array[$x][$y]."'<br>";
or this way: while (list ($key) = each ($array))
        while (list ($key_two) = each ($array[$key]))
                print "\$array[$key][$key_two] = '".$array[$key][$key_two]."'<br>"
There are lots of other ways to do this. Hope this helps! Zak Greant Creative Director Nucleus Information Service Inc. "A camel is a horse designed by a committee." - Alex Issigonis (Designer of the Austin Mini)

« previous php.windows (#573) next »