tags:

views:

37

answers:

2

How come when I echo $p, the variable which Im trying to fetch using this loop doesnt get displayed in the path.

$name_image2="picture.jpg";
for ($i=2; $i<=$nr_of_pics; $i++){
     $img='name_image'.$i;

echo $$img; gives me this: 'picture.jpg' which is correct. but when echoing $p like this:

   $p="/SV/main/temp_images/$$img"; echo $p;

I get this: SV/main/temp_images/name_image2 --> the variable 'name_image2' doesnt get called here, why? I want it to say: SV/main/temp_images/picture.jpg

Thanks

+2  A: 

Try $p="/SV/main/temp_images/{${$img}}";

When PHP is parsing the string and comes to a $, it looks at the next character to see if it makes a valid variable name. If not, it moves on. In this case, that means that the second $ is correctly interpreted, but the first one has already been passed by. The answer is to enclose the inner expression in brackets, so that it will be parsed before the outer one is.

JacobM
+1  A: 
$p = "/SV/main/temp_images/" . $$img;

Ought to fix it.

Also, I would recommend learning how to use arrays. They are a much better way to have a set of data instead of variable variables.

Jani Hartikainen