php循环中的“ if”

时间:2019-11-07 14:30:57

标签: php loops if-statement

我正试图通过循环字符串

来缩短$vat1 - $vat10$的这段代码
$vat1 = htmlspecialchars($_POST["vat1"]);
if ($vat1 != "zw" &&  $vat1 != "") {
    $vat1 .= "%";
}
$vat2 = htmlspecialchars($_POST["vat2"]);
if ($vat2 != "zw" &&  $vat2 != "") {
   $vat2 .= "%";
}
....

但是由于其中包含if语句,它无法正常工作:

for ($x; $x <=10; $x++){
    $vat = 'vat' . $x;
    $$vat = htmlspecialchars($_POST["vat" . $x]);
    if ($$vat != "zw" &&  $$vat != "") {
        $$vat .= "%";
    }
}

我已阅读在循环内使用三元运算符,因此我正在尝试像这样进行操作:

for ($x; $x <=10; $x++){
    $vat = 'vat' . $x;
    $$vat = htmlspecialchars($_POST["vat" . $x]) . 
                            ($$vat != "zw" &&  $$vat != "") ? $$vat .= "%" : "";
}

但是仍然不能取得很好的效果。你能告诉我怎么做对吗?

1 个答案:

答案 0 :(得分:0)

您可以使用${'vat.$x}构造

来代替可变变量
$_POST = ['vat1' => 1, 'vat2' => 'zw', 'vat3' => '', 'vat4' => 4, 'vat5' => 5,
          'vat6' => 6, 'vat7' => 7, 'vat8' => 8, 'vat9' => 9, 'vat10' => 10
        ];

for ($x=1; $x <=10; $x++) {
//   ^^^^    Note I started the loop at a specific place 1 in this case
    ${'vat'.$x} = htmlspecialchars($_POST['vat'.$x]);
    if (${'vat'.$x} != "zw" &&  ${'vat'.$x} != "") {
        ${'vat'.$x} .= "%";
    }
}

echo 'vat1 = ' . $vat1.PHP_EOL;
echo 'vat2 = ' . $vat2.PHP_EOL;
echo 'vat3 = ' . $vat3.PHP_EOL;
echo 'vat4 = ' . $vat4.PHP_EOL;
echo 'vat5 = ' . $vat5.PHP_EOL;
echo 'vat6 = ' . $vat6.PHP_EOL;
echo 'vat7 = ' . $vat7.PHP_EOL;
echo 'vat8 = ' . $vat8.PHP_EOL;
echo 'vat9 = ' . $vat9.PHP_EOL;
echo 'vat10 = ' . $vat10.PHP_EOL;

结果

vat1 = 1%
vat2 = zw
vat3 = 
vat4 = 4%
vat5 = 5%
vat6 = 6%
vat7 = 7%
vat8 = 8%
vat9 = 9%
vat10 = 10%

或者您可以坚持使用变量变量解决方案

for ($x=1; $x <=10; $x++) {
//   ^^^^    Again start the loop at a specific place 1 in this case

    $t = 'vat'.$x;
    $$t = htmlspecialchars($_POST['vat'.$x]);
    if ($$t != "zw" &&  $$t != "") {
        $$t .= "%";
    }
}

还会产生

vat1 = 1%
vat2 = zw
vat3 = 
vat4 = 4%
vat5 = 5%
vat6 = 6%
vat7 = 7%
vat8 = 8%
vat9 = 9%
vat10 = 10%

因此,基本上所有代码错误是您没有正确启动for循环。