jeudi 7 novembre 2019

"if" inside php's loop

i'm trying to make this code of $vat1 - $vat10$ shorter by looping string

$vat1 = htmlspecialchars($_POST["vat1"]);
if ($vat1 != "zw" &&  $vat1 != "") {
$vat1 .= "%";
}
$vat2 = htmlspecialchars($_POST["vat2"]);
if ($vat2 != "zw" &&  $vat2 != "") {
$vat2 .= "%";
}
....

But it's not working correctly because of if statement inside it:

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

I have read to use ternary operator inside loop, so I'm trying to make sth like this:

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

But still it doesn't make a good effect. Can you tell me how to make it right?

Aucun commentaire:

Enregistrer un commentaire