如果数组中的任何字段不为空,则显示消息 - PHP / [POST] 表单


If any field in array is not empty, display message - PHP / [POST] form

我有一个包含 25+ 字段的表单。如果数组中的任何字段不为空,我想显示一条消息。

$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');

我查看了类似的 SO 问题,以验证所有字段是否不为空,即:

$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.";
}

我该如何做相反的事情 - 如果数组中的任何一个或多个字段不为空,则显示一条消息?

提前感谢!

我想你想看看NOT运算符。

你可以这样写:

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

有关更多信息,请参阅手册:http://php.net/manual/en/language.operators.logical.php

if中做相反的比较:

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