how to change php variable name in a loop? how to change php variable name in a loop? php php

how to change php variable name in a loop?


Use ${'varname'} syntax:

for($i=1; $i <= 5; $i++) {    ${'file' . $i} = $i;}

However, it's often better to use arrays instead of this.


There is a way to do this:

for($i = 1; $i <= 5; $i++) {    ${'file'.$i} = ...;}

But it is a bad idea to do this. Why is it a bad idea? Because this is what arrays are meant for. Do this instead:

for($i = 1; $i <= 5; $i++) {    $file[$i] = ...;}

(NB. It is the usual convention to start array keys at 0 rather than 1, but you do not have to do so.)


it is possible to do what you want, but creating variables on the fly seems an unusual way to solve a problem like this (i could be wrong)

I would suggest storing the filenames in an array, that way you can easily iterate over the files later on, or add an extra file and not have to change any hardcoded variable names

    $myfiles = array();    for ($i=1; $i<=5; $i++) {       $myfiles["file$i"] = "value set in loop";    }    //if you want to use the values later    $file5_value = $myfiles["file5"];    //if you want to loop through them all    foreach ($myfiles as $key => $val) {      echo "$key -> $val\n";    }