John Siniger
John Siniger

Reputation: 885

Store for loop iteration variable into a new incremented variable

Hello I would like to store variable value for each for iteration into a new variable with new name. I need the final result to be variable not array.

FOR LOOP:

for($i = 0;$i < count($_FILES['file']['name']);$i++) {
$file = rand(1000,100000)."-".$_FILES['file']['name'][$i];
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);     
}

Than inside this loop I need something like that:

$data1 = $final_file;

Where $data1 should increment the name each time the loop goes.

at the end it should generate something like this:

$data1 = $final_file; - final_file have value of the first loop iteration
$data2 = $final_file; - final_file have value of the second loop iteration
$data3 = $final_file; - ....
$data4 = $final_file;
$data5 = $final_file;

Upvotes: 0

Views: 54

Answers (2)

edruid
edruid

Reputation: 703

Setting a variable dynamically can be done using an extra $:

$i = 1;
$variable_name = 'data' . $i;
$$variable_name = 'my value';

After that code $data1 will be set to "my value".

However, I would encourage you to use an array with the values instead.

Upvotes: 1

mario.van.zadel
mario.van.zadel

Reputation: 2949

$data should be an array. Fill the array in the for loop with $data[$i] = $final_filename;

Later you can access the file names like this: $data[1], $data[2], $data[3], ...

Upvotes: 0

Related Questions