PHP-循环未按预期运行

PHP-循环未按预期运行,php,Php,我正在使用PHP中的for循环,但它没有按预期工作。循环使用自己的验证脚本将表单输出到页面。然而,一旦运行,循环就永远不会结束 for ($noemployments=0; $noemployments < 3; $noemployments++) { if ($noemployments >=9) { break 2; } $noemploymentsErr.$noemployments=""; if ($_SERVER['RE

我正在使用PHP中的for循环,但它没有按预期工作。循环使用自己的验证脚本将表单输出到页面。然而,一旦运行,循环就永远不会结束

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>";

 }
for($noemployments=0;$noemployments<3;$noemployments++){
如果($noemployments>=9){
破口2;
}
$noemploymentsErr.$noemployments=“”;
如果($\u服务器['REQUEST\u METHOD']==“POST”){
if(空($\u POST['no\u reports.$noemployments'])){
$noemploymentsErr.$noemployments=“这是必填字段。”;
}否则{
$no_empreturns.$noemployments=test_输入($_POST['no_empreturns.$noemployments']);
如果(!preg_match(“/^[a-zA-Z0-9_-]*$/”,则$no_返回。$noemployments)){
$noemploymentsErr.$noemployments=“输入了非法字符。”;
}
}
}
打印“雇佣名称”。$noemployments。“:
";
打印“”$noemploymentsErr.$noemployments.“”;
}
有什么建议吗

$noemploymentsErr.$noemployments="";
不做你想做的事。它每次通过循环将
$noemployments
设置为,并将字符串设置为空,其计算结果为
0
0<3
。所以循环永远不会结束

最好使用数组:

$noemploymentsErr[$noemployments] = "";
但如果以后不使用此选项,则无需单独保留错误,只需:

$noemploymentsErr = "";

在这一行:
$noemploymentsErr.$noemployments=“”
您实际上正在设置
$noemployments=“
”,然后在调用++时在循环中进行交互-它被转换为一个数字(0)并添加+1-1。因此,您实际上在每次迭代时都会重置循环变量,从而使循环永远不会停止运行。