Haini Haini - 4 months ago 6
PHP Question

Creating, Accessing and understanding multidimensional arrays in php

I have implemented the following small example:

$nodeList;
for($i = 0; $i < 10;$i++) {
$nodeList[$i] = $i;
for($j = 0; $j < 3;$j++) {
$nodeList[$i][$j] = $j;
}
}

foreach($nodeList[0] as $nodeEl) {
print "NodeEl: ".$nodeEl." | ";
}

print nl2br("\n\r");

$testList = array
(
array(1,2,3),
array(4,5,6),
array(7,8,9),
array(10,11,12),
);
foreach($testList[0] as $testEl) {
print "TestEl: ".$testEl." | ";
}


Where the output for
$nodeList
is
null
(var_dump / print_r too) and the output for
$testList
is
TestEl: 1 | TestEl: 2 | TestEl: 3
, as expected.

In my understanding those two solutions should create roughly the same output - but instead there is no output for the first one at all. Because the second dimension of the array is not even created.

Reading up on http://php.net/manual/de/language.types.array.php creates the strong feeling that the [] operator is only for dereferencing / accessing of the array, but then again the docs provide a sample where they assign a value to a certain key the same way I do
$arr["x"] = 42
.

What is the difference between these two ways of array access?

How can I achieve filling a n-dimensional array in a way similar to the way I try to fill
$nodeList
?

Answer

You should make sure to have error reporting turned on, because warnings are generated for your code:

E_WARNING :  type 2 -- Cannot use a scalar value as an array -- at line 7

This concerns the following statement:

$nodeList[$i] = $i;

If you want to create a 2D array, there is no meaning in assigning a number on the first level. Instead you want $nodeList[$i] to be an array. PHP does that implicitely (creating the array) when you access it with brackets [...], so you can just leave out the offending statement, and do:

for($i = 0; $i < 10;$i++) {
    for($j = 0; $j < 3;$j++) {
        $nodeList[$i][$j] = $j;
    }
}

You can even leave out the $j in the last bracket pair, which means PHP will just add to the array using the next available numerical index:

for($i = 0; $i < 10;$i++) {
    for($j = 0; $j < 3;$j++) {
        $nodeList[$i][] = $j;
    }
}
Comments