how to change php variable name in a loop?

前端 未结 5 1281
天命终不由人
天命终不由人 2020-12-05 04:58

Lets say I have a variable called $file and the for loop: for($i=1; $i <= 5; $i++) {}

For each iteration of the for loop, the $i value w

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 05:34

    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";
        }
    

提交回复
热议问题