NYCPHP Meetup

NYPHP.org

[nycphp-talk] Array Reference Strangeness

Flavio daCosta nyphp at n0p.net
Mon May 28 08:55:39 EDT 2007


Remember from the php manual: References in php are not like C pointers.
 (they are symbol table aliases)

On 05/28/2007 12:20 AM, Michael B Allen wrote:
<snip>
> for ($i = 0; $i < 3; $i++) {
>     $arr = array("a$i");
>     $top[] = &$arr;
>     $arr["key$i"] = "val$i";
> }
</snip>

So what that is saying is that $arr and $top[n] are both pointing to the
same symbol table (or zval), so each iteration of your loop, you never
/create/ a new zval, in the first line, you (re)assign new data in the
zval which $arr points to. The second line keep pushing another
reference to the same zval.

I usually do all my work to $arr first and then push a *copy* onto top,
however, in order to get the effect of what you wanted "I want to be
able to update elements in $arr after it has been added to $top", you
could do something like assign the value into $top first, and then grab
a reference to that value.

<?php
$top = array();

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

print_r($top);


Hope that helps.

flav




More information about the talk mailing list