循环的PHP语法

时间:2017-03-03 12:37:25

标签: php loops

我正在尝试将以下PHP转换为循环。我过去已经完成了循环,但是这个循环很难得到正确的语法。

    $answer1= $_POST['answer1'];
    $answer2= $_POST['answer2'];
    $answer3= $_POST['answer3'];
    $answer4= $_POST['answer4'];
    $answer5= $_POST['answer5'];
    $answer6= $_POST['answer6'];
    $answer7= $_POST['answer7'];
    $answer8= $_POST['answer8'];
    $answer9= $_POST['answer9'];
    $answer10= $_POST['answer10'];
    $answer10= $_POST['answer10'];

到目前为止,我一直在使用下面显示的循环。

for ($x = 1; $x <= 10; $x++) {
    $answer . $x = $_POST['answer' . $x];

    $b = "\$answer" . $x;

    $a = $b . "= \$_POST[" . $b . "]";
}

2 个答案:

答案 0 :(得分:0)

我认为您应该使用{}运算符来动态评估php内容以进行动态var生成

for ($x = 1; $x <= 10; $x++) { 
  ${"answer" . $x} = $_POST['answer' . $x];

}

http://php.net/manual/en/language.variables.variable.php

答案 1 :(得分:0)

我会将$answer$x{}一起包装,因此它会根据其他两个变量的值创建变量

for ($x = 1; $x <= 10; $x++) {
    {$answer . $x} = $_POST['answer' . $x];

    $b = "\$answer" . $x;

    $a = $b . "= \$_POST[" . $b . "]";
}