tags:

views:

108

answers:

1

I have several variables named $name_image1, $name_image2 etc. (all ending with a nr).

Can you see what I am trying to do here below:

for ($i = 0; $i < $nr_of_pics; $i++){
  rename( $temp_img_path . $name_image[$i], $new_img_path . 'thumbs/'.$name_image[$i] );
}

I want to skip doing alot of if statements. Is it possible to alter a variable name as above, because it wont work for me, it says "undefined variable".

thanks

+3  A: 

While I won't say this is "good advice" (definitely not BCP), have you checked out variable variables?

for ($i = 1; $i <= $nr_of_pics; ++$i) {
    $image = 'name_image' . $i;
    if (!isset($$image)) continue; // error checking
    rename($temp_img_path.$$image, $new_img_path.'thumbs/'.$$image);
}

Note: that snippet makes the assumption that the image numbers start at "1" like you said in your post, instead of "0" where your code started; if this is not the case, change the first line back to:

for ($i = 0; $i < $nr_of_pics; ++$i) {

The problem with your snippet is that $name_image[$i] is the syntax to access the element at index $i in an array named $name_image, which you have not defined. The only way to access a variable without "knowing it's name" at code-time is to use a variable variable, which as the manual will explain, evaluates the contents of the rightmost variable (that is, the contents of $image in $$image) as the name of a variable it should access.

I was going to post a long winded explantion here, but the manual entry should make good sense.

Dereleased
thanks man... good info!
Camran