<p>Why does the following code not work as I was expecting?</p>

<pre><code>&lt;?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]] =&amp; $area;
    } elseif ($row[1]) {
        $section = array();
        $area[$row[1]] =&amp; $section;
    } elseif ($row[2]) {
        $section[] = $row[2];
    }
}
print_r($root);
</code></pre>

<p>Expected result:</p>

<pre><code>Array(
    [Area1] =&gt; Array(                         
            [Section1] =&gt; Array(
                    [0] =&gt; Location1
                )                   
        )
    [Area2] =&gt; Array(           
            [Section2] =&gt; Array(              
                    [0] =&gt; Location2
                )                   
        )
)
</code></pre>

<p>Actual result:</p>

<pre><code>Array(
    [Area1] =&gt; Array(                         
            [Section2] =&gt; Array(
                    [0] =&gt; Location2
                )                   
        )
    [Area2] =&gt; Array(           
            [Section2] =&gt; Array(              
                    [0] =&gt; Location2
                )                   
        )
)
</code></pre>

[{'answer_id': 42885, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 3, 'selected': True, 'text': '<p>If you modify your code on two lines as follows:</p>\n\n<pre><code>$area = array();\n\n$section = array();\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>unset($area);\n$area = array();\n\nunset($section);\n$section = array();\n</code></pre>\n\n<p>it will work as expected.</p>\n\n<p>In the first version, <code>$area</code> and <code>$section</code> are acting as "pointers" to the value inside the <code>$root</code> array.  If you reset the values first, those variables can then be used to create brand new arrays instead of overwriting the previous arrays.</p>\n'}, {'answer_id': 42913, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 1, 'selected': False, 'text': '<p>This will also works:</p>\n\n<pre><code>$root[$row[0]] = array();\n$area =&amp; $root[$row[0]];\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/42876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486/']