tags:

views:

52

answers:

4

Why do I get 'undefined variable $image_src' with this code:

$image_src1=null;
$image_src2=null;
for ($i=1; $i<=$nr_of_pics; $i++) {
     $image_src.$i = $image_id.'_'.$i;
     }

    echo $image_src1;

I want the $image_src.$i to refer to the variable $image_src1 or $image_src2 depending on how many loops there are... But it wants to find the variable $image_src without an ending nr, which doesn't exist, because I want it to find the variable with the '$i' ending!

It doesn't get that the $i is for the last number in the variable $image_src name!

Rest of the code is fine!

Thanks

+1  A: 

Try referring to it like this:

${"image_src$i"} = $image_id.'_'.$i;

or for readability (even though it isn't much better):

$name = "image_src".$i;
$$name = $image_id.'_'.$i;
Vegard Larsen
+4  A: 

Change it to:

${'image_src' . $i} = $image_id . '_' . $i;

or you can also do it this way:

$var = 'image_src' . $i;
$$var = $image_id . '_' . $i;

See variable variables from the PHP manual.

Edit: I'm assuming your question is a simplified example of your problem because of course you can always use arrays for this:

$image_src = array();
for ($i=1; $i<=2; $i++) {
  $image_src[$i] = $image_id . '_' . $i;
}
echo $image_src[1];

which makes more sense than variable variables for something like this.

cletus
+5  A: 

While others have correctly answered with ${"image_src$i"}, I'd like to also recommend you use arrays for what you're trying to accomplish

$image_src = array();
for ($i = 1; $i <= $nr_of_pics; $i++) {
 $image_src[$i] = $image_id.'_'.$i;
}

echo $image_src[1];
Matt
+1  A: 

You need to use this syntax,

    ${'image_src'.$i} = $image_id.'_'.$i;
ZZ Coder