Two dimentional array
| From: | Nasir Ali | Date: | Thu, 22 Jun 2000 11:23:57 +0000 |
| Subject: | Two dimentional array | ||
| Groups: | php.windows | ||
| Request: | Send a blank email to php-windows+get-580@lists.php.net to get a copy of this message | ||
At 08:14 PM 6/21/00 -0600, you wrote:
>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!
Thanks Zak,
It's really helpfull. Now I feel like dumb axx hole because I following
code is not working... What am I doing wrong????
<?php
$myarray[0][0] = 'A';
$myarray[0][1] = 'B';
$myarray[0][2] = 'I';
$myarray[1][0] = 'C';
$myarray[1][1] = 'D';
$myarray[1][2] = 'J';
$myarray[2][0] = 'E';
$myarray[3][0] = 'F';
$myarray[3][1] = 'Z';
$myarray[3][2] = 'G';
$myarray[3][3] = 'Q';
$myarray[4][0] = 'H';
for($x=0; $x < count($myarray); $x++)
for($y=0; $y < count($myarray[$x]); ++$y)
echo $myarray[$x][$y]."<br>"; //it gives me parse error on this line
?>