Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Arrays, and References

Why does the following code not work as I was expecting?

<?php
$data = array(
    array('Area1', null, null),
    array(null, 'Section1', null),
    array(null, null, 'Location1'),
    array('Area2', null, null),
    array(null, 'Section2', null),
    array(null, null, 'Location2')
);
$root = array();
foreach ($data as $row) {
    if ($row[0]) {
        $area = array();
        $root[$row[0]] =& $area;
    } elseif ($row[1]) {
        $section = array();
        $area[$row[1]] =& $section;
    } elseif ($row[2]) {
        $section[] = $row[2];
    }
}
print_r($root);

Expected result:

Array(
    [Area1] => Array(                         
            [Section1] => Array(
                    [0] => Location1
                )                   
        )
    [Area2] => Array(           
            [Section2] => Array(              
                    [0] => Location2
                )                   
        )
)

Actual result:

Array(
    [Area1] => Array(                         
            [Section2] => Array(
                    [0] => Location2
                )                   
        )
    [Area2] => Array(           
            [Section2] => Array(              
                    [0] => Location2
                )                   
        )
)
like image 300
grom Avatar asked Oct 15 '22 19:10

grom


2 Answers

If you modify your code on two lines as follows:

$area = array();

$section = array();

to this:

unset($area);
$area = array();

unset($section);
$section = array();

it will work as expected.

In the first version, $area and $section are acting as "pointers" to the value inside the $root array. If you reset the values first, those variables can then be used to create brand new arrays instead of overwriting the previous arrays.

like image 57
pix0r Avatar answered Oct 18 '22 12:10

pix0r


This will also works:

$root[$row[0]] = array();
$area =& $root[$row[0]];
like image 38
grom Avatar answered Oct 18 '22 14:10

grom