how to change php variable name in a loop?

前端 未结 5 1305
天命终不由人
天命终不由人 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:38

    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.)

提交回复
热议问题