how to change php variable name in a loop?

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

    See PHP's manual on Variable Variables.

    $var_name = '';
    for ($i = 0; $i < 5; $i++)
    {
      $var_name = 'file' . $i;
    
      // reference $$var_name now.
      $$var_name = 'foo';
    }
    
    var_dump($file1);
    var_dump($file2);
    var_dump($file3);
    var_dump($file4);
    var_dump($file5);
    

    demo

提交回复
热议问题