问题描述:

I have a form with 25+ fields. I want to display a message if ANY of the fields in the array are NOT empty.

$customfields = array('q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12', 'q13', 'q14', 'q15', 'q16', 'q17', 'q18', 'q19', 'q20', 'q21', 'q22', 'q23', 'q24');

I've taken a look at similar SO questions for verifying that all fields are not empty, i.e.:

$error = false;

foreach($customfields as $field) {

if (empty($_POST[$field])) {

$error = true;

}

}

if ($error) {

echo "Here's an awesome message!";

} else {

echo "None for you, Glen Coco.";

}

How do I do the opposite - display a message if ANY one or more than one fields in the array are not empty?

Thanks in advance!

网友答案:

Do the opposite comparison in the if:

$error = false;
foreach($customfields as $field) {
  if (!empty($_POST[$field])) {
    $error = true;
    break; // get out of foreach loop
  }
}
网友答案:

I think you want to take a look into the NOT operator.

You can just write this:

if (!empty($_POST[$field])) {
  //^ See here the NOT operator
    $error = true;
}

For more information see the manual: http://php.net/manual/en/language.operators.logical.php

相关阅读:
Top