reference array value from inside itself

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

reference array value from inside itself

Post 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
?>
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: reference array value from inside itself

Post 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:
Post Reply