I don’t do php for quite a while and now i’ve decided to make a little script but i’ve ran into a problem i had once before and managed to solve by myself but now i’m not being able to.
Let’s say i have ‘n’ arrays like so…
$numbers1=array('32','16','29','41','36');
$numbers2=array('13','50','47','7','39');
$numbers3=array('3','4','29','35','31');
and then i want to use a ‘for loop’ to generate the array names and output certain elements of the arrays and/or the whole array itself like so…
for($count1=1;$count1<=3;$count1++)
{
$num1='numbers'.$count1;
print_r($$num1); //this outputs what's inside all arrays as expected
echo $$num1[0];
}
The “echo $num1[0]” is the problem and it’s on there just to illustrate that i wanted to ‘echo’ the contents from elements 0 of all arrays obtaining the following output “32133”.
I’ve made a similar question on stackoverflow a long time ago when i was getting started with php but the aswers on that question don’t work for this situation and neither the 2 hours i’ve lost googling together with searching here on stackoverflow.
You need to use
{}, so PHP knows how to interpret your variable.Try that. That should work the way you want.
$$num1[0]is being interpreted as${$num1[0]}(so PHP is looking for$n).DEMO: http://codepad.org/yn1JUG5U