Hey,

I'm having trouble with array references.

Consider the following code:

#!/usr/bin/php -q
<?php
$top = array();

for ($i = 0; $i < 3; $i++) { 
    $arr = array("a$i");
    $top[] = &$arr;
    $arr["key$i"] = "val$i";
}

print_r($top);
?>

I want to be able to update elements in $arr after it has been added to
$top. However, the assignment appears to make a copy (adding elements to
$arr are not in the $arr added to $top). So I thought perhaps I need to
assign $arr to $top by reference with '&'. However this yields strange
behavior. Even though I feel like I'm creating a new $arr with each
iteration of the loop, the reference has not changed in $top. Elements
are updated in $arr within $top but it seems there is only one $arr.

The output shows that the keys and values added are all the same:

$ ./test.php 
Array
(
    [0] => Array
        (
            [0] => a2
            [key2] => val2
        )

    [1] => Array
        (
            [0] => a2
            [key2] => val2
        )

    [2] => Array
        (
            [0] => a2
            [key2] => val2
        )

)

The behavior I want would yield:

Array
(
    [0] => Array
        (
            [0] => a0
            [key0] => val0
        )

    [1] => Array
        (
            [0] => a1
            [key1] => val1
        )

    [2] => Array
        (
            [0] => a2
            [key2] => val2

What's the problem?

Mike

-- 
Michael B Allen
PHP Active Directory Kerberos SSO
http://www.ioplex.com/
_______________________________________________
New York PHP Community Talk Mailing List
http://lists.nyphp.org/mailman/listinfo/talk

NYPHPCon 2006 Presentations Online
http://www.nyphpcon.com

Show Your Participation in New York PHP
http://www.nyphp.org/show_participation.php

Reply via email to