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


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

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

echo "$test[0]"; // Outputs 4
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:  
Please explain.
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
        $array[$i][$j] = $i + $j;
        echo "Array[$i][$j]: $array[$i][$j]\n";
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:
        $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