I'm confused about how PHP variable references work. In the examples below, I want to be able to access the string hello either as $bar[0]
or $barstack[0][0]
. It would seem that passing the array by reference in step 1 should be sufficient.
The second example does not work. $foostack[0]0]
is the string hello, but $foo[0]
doesn't exist. At some point, the first element of $foostack becomes a copy of $foo, instead of a reference.
The problem lies in the first line of step 2: When I push a reference on, I expect to pop a reference off. But array_pop
returns a copy instead.
Others have told me that if I have to worry about references and copies, then PHP is not the right language for me. That might be the best answer I'm going to get.
FWIW, in order for var_dump
to be useful, it needs to display some property that distinguishes between a reference and a copy. It does not. Maybe there's another function?
My first PHP project seems to be going badly. Can someone help shed some light on the problems with this code?
<?php
echo "// This works!\n<br />" ;
// step 1
$bar = array() ;
$barstack = array( &$bar ) ;
// step 2
array_push( $barstack[0], 'hello' ) ;
// results
echo count( $barstack[0] ) .';' .count( $bar ) ;
echo "\n<br />// This doesn't :(\n<br />" ;
// step 1
$foo = array() ;
$foostack = array( &$foo ) ;
// step 2
$last = array_pop( $foostack ) ;
array_push( $last, 'hello' ) ;
array_push( $foostack, &$last ) ;
// results
echo count( $foostack[0] ) .';' .count( $foo ) ;
echo "\n<br />// Version:\n<br />" ;
echo phpversion() ."\n" ;
?>
The results can be viewed at the following URL:
http://www.gostorageone.com/tqis/hi.php
Version is 4.3.10. Upgrading the server is not practical.
Desired outcomes:
- Explain the obvious if I've overlooked it
- Is this a bug? Any workarounds?
Thanks!
-Jim
var_dump
shows references, it's signalled with an&
in front of the value. I've added an answer that explains step by step what happens, I think you're just missing thatarray_pop
returns a value always, not a reference/alias. I've added a working example below as well. – Airburst