Page 1 of 1

reference array value from inside itself

Posted: Fri Oct 08, 2010 4:32 pm
by flying_circus
I'd like to reference an array value from within itself. Is there a way to do this?

example:

Code: Select all

<?php
$test = array('1' => 'foo',
              '2' => 'bar',
              'default' => $test['2']);

print $test['2']; //bar
print $test['default']; //bar
?>

Re: reference array value from inside itself

Posted: Fri Oct 08, 2010 4:43 pm
by Jonah Bron
I tested it, and this works:

Code: Select all

$test = array('1' => 'foo',
    '2' => 'bar',
    '3' => &$test
);

echo $test['3']['1']; // "foo"
The trick is the pass-by-reference ampersand. You had better be careful: this could easily get you into an infinite recursion. Try print_r() on $test :mrgreen: