galexcd 0 Report post Posted October 25, 2007 Ok i can't believe I need help in php but I can't figure this out... If i have an array, lets say called test, how do i get a certain value from that array when referencing it dynamically by either a string or another variable?Example: $test=array(1,2,5);$name="test";//Doesn't work:echo $$name[0];/Doesn't work:echo ${$name}[0]; Share this post Link to post Share on other sites
jlhaslip 4 Report post Posted October 25, 2007 <?php$test=array(1,2,5);$name = &$test; // check this lineecho 'print_r $test';echo '<br />';echo '<pre>';print_r ($test);echo '</pre>';echo '<br />';echo 'print_r $test[0]';echo '<br />';print_r ($test[0]);echo '<br />';echo '<br />';echo 'print_r $name';echo '<pre>';print_r ($name);echo '</pre>';echo '<br />';echo 'print_r $name[0]';echo '<pre>';print_r ($name[0]);echo '</pre>';?> Note line 2 and the prefix for references, compared to your code. Share this post Link to post Share on other sites
galexcd 0 Report post Posted October 26, 2007 I was hoping not to use references but all right i guess i must... Share this post Link to post Share on other sites
pointybirds 0 Report post Posted October 26, 2007 Alex,I believe the evil eval could be your friend here: $test=array(1,2,5);$name="test";eval ("\$blah = $${name}[2];");echo $blah; Use it with care and good luck! Share this post Link to post Share on other sites
galexcd 0 Report post Posted October 26, 2007 Does eval parse differently than regular php code? I always assumed it was the same. I shall try this and report back here if it works. Share this post Link to post Share on other sites
pointybirds 0 Report post Posted October 26, 2007 eval will run the contents of the string as code, however it interpolates variables too, so the above code will replace $name with "test", then uses $test in the eval. Share this post Link to post Share on other sites
pop 0 Report post Posted November 5, 2007 i test you code, work. my version php 5.2 <?php$test=array(1,2,5);$name="test";echo ${$name}[2]; // print 5 ?!?> Share this post Link to post Share on other sites
galexcd 0 Report post Posted November 5, 2007 Hmm it didn't work for me... Perhaps its because I have an older version? Share this post Link to post Share on other sites
jlhaslip 4 Report post Posted November 5, 2007 works for me, toophp 5.2.4 Share this post Link to post Share on other sites
pop 0 Report post Posted November 5, 2007 you can see php version if you run<?php phpinfo(); ?> Share this post Link to post Share on other sites