I am working with a for loop in PHP which is not working as intended. The loop outputs a form to the page with its own validation script. However, once run, the loop never ends!
for ($noemployments=0; $noemployments < 3; $noemployments++) {
if ($noemployments >=9) {
break 2;
}
$noemploymentsErr.$noemployments="";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST['no_empreturns".$noemployments"'])) {
$noemploymentsErr.$noemployments = "This is a required field.";
} else {
$no_empreturns.$noemployments = test_input($_POST['no_empreturns".$noemployments"']);
if (!preg_match("/^[a-zA-Z0-9_-]*$/", $no_empreturns.$noemployments)) {
$noemploymentsErr.$noemployments = "Illegal characters have been entered.";
}
}
}
print "<label for='no_returns'>Employment Name".$noemployments.":</label>
<input type='text' id='no_returns' class='form-control' name='no_empreturns".$noemployments."' placeholder='Employment name' maxlength='20'>";
print "<strong>".$noemploymentsErr.$noemployments."</strong>";
}
Any suggestions?
$noemploymentsErr.$noemployments="";You're actually setting$noemployments=""and then on the loop interation when ++ is called - it's being casted to a number (0) and +1 added - 1. So you're actually resetting your loop variable at every iteration causing the loop to never stop running.