简体   繁体   English

PHP foreach函数中只能运行一次

[英]PHP foreach in a function only runs once

I'm trying to run a foreach loop to check if one of the required fields in a form is empty, and output the missing fields through an error array. 我正在尝试运行一个foreach循环,以检查表单中的必填字段是否为空,并通过错误数组输出缺少的字段。 Each of the variables is assigned to a $_POST variable. 每个变量都分配给$ _POST变量。

However, once I call the function: 但是,一旦我调用该函数:

fields_empty($requiredFields, $fieldErrors);

It only runs once, and not looping through the error. 它只运行一次,不会遍历错误。 Here's the full source code: 这是完整的源代码:

$requiredFields = array(
    "First Name"=>$fname,
    "Last Name"=>$lname,
    "Email"=>$email,
    "Password"=>$pass1,
    "Confirm Password"=>$pass2,
    "Country"=>$country,
    "Address 1"=>$addr1,
    "City"=>$city,
    "State"=>$state,
    "Postal Code"=>$pcode,
    "Phone Number"=>$phone
);

$fieldErrors = array();

function fields_empty($requiredFields, $fieldErrors) {
    global $fieldErrors;
    foreach($requiredFields as $name => $field) {
        if (empty($field)) {
            array_push($fieldErrors, "$name is required.<br>");
            return true;
        }
    }
}

fields_empty($requiredFields, $fieldErrors);
print_r($fieldErrors);

Output in browser: 在浏览器中输出:

Array (
    [0] => First Name is required.
)

Also, this only happens when it's in a function. 同样,只有在函数中才会发生这种情况。 If I execute it without a function, it shows all the missing fields. 如果我不带函数执行它,它将显示所有缺少的字段。

Remove return from your function. 从函数中删除return What return does is terminate the function and return whatever is passed with the return , here its set to true . return的作用是终止函数并返回随return传递的所有内容,此处将其设置为true Removing return will keep the loop running. 删除回车将使循环保持运行状态。

function fields_empty($requiredFields, $fieldErrors) {
   global $fieldErrors;
   foreach($requiredFields as $name => $field) {
      if (empty($field)) {
         array_push($fieldErrors, "$name is required.<br>");
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM