简体   繁体   中英

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. Each of the variables is assigned to a $_POST variable.

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. What return does is terminate the function and return whatever is passed with the return , here its set to 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>");
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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