1

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?

1
  • On this line: $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. Commented Sep 2, 2015 at 18:13

1 Answer 1

1
$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 = "";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.