faqts : Computers : Programming : Languages : PHP : kms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

15 of 30 people (50%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How does 2D value assignment/reading work in PHP? See example.

Aug 8th, 2002 03:50
balasubramaniam palanisamy, Bryan W,


Example:
$test[0]=4;
echo "$test[0]"; // Outputs 4
$test2[0][0]=5;
echo "$test2[0][0]"; //Outputs Array[0]
____________________________________________________________
The first two lines of code act as expected and output 4.
The second two lines of code prouduce an output I don't understand:  
Array[0].
Please explain.
Answer:
_______
It turns out that the problem I was experiencing has nothing to do with 
the array, 'test2' itself.  The problem was in how I was echoing the 
output.  I should have used:
echo $test2[0][0];
There is a way to resolve ambuiguity in using array names with variable 
variables(see the PHP manual) -- I wonder if there is a similar way to 
resolve ambiguity in echoing array output?
------------------------------------------------------------------------
Best Answer :
_____________
to echo multidimensional arrays put the variable in {}'s
example:
<?php
for($i=0;$i<=2;$i++)
{
    for($j=0;$j<=2;$j++)
    {
        $array[$i][$j] = $i + $j;
        echo "Array[$i][$j]: $array[$i][$j]\n";
    }
}
?>
displays:
Array[0][0]: Array[0] 
Array[0][1]: Array[1] 
Array[0][2]: Array[2] 
Array[1][0]: Array[0] 
Array[1][1]: Array[1] 
Array[1][2]: Array[2] 
Array[2][0]: Array[0] 
Array[2][1]: Array[1] 
Array[2][2]: Array[2] 
while the code:
<?php
for($i=0;$i<=2;$i++)
{
    for($j=0;$j<=2;$j++)
    {
        $array[$i][$j] = $i + $j;
        echo "Array[$i][$j]: {$array[$i][$j]}\n";
    }
}
?>
will properly display the values as such:
Array[0][0]: 0 
Array[0][1]: 1 
Array[0][2]: 2 
Array[1][0]: 1 
Array[1][1]: 2 
Array[1][2]: 3 
Array[2][0]: 2 
Array[2][1]: 3 
Array[2][2]: 4