Alex
Alex

Reputation: 151

PHP - Loop not behaving as expected

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?

Upvotes: 1

Views: 43

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

$noemploymentsErr.$noemployments="";

Doesn't do what you think. It sets $noemployments to and empty string every time through the loop, which evaluates to 0 and 0 < 3. So the loop never ends.

Better would be to use an array:

$noemploymentsErr[$noemployments] = "";

But if you don't use this later then there is no need to keep the errors individually, just:

$noemploymentsErr = "";

Upvotes: 1

Related Questions