【问题标题】:If any field in array is not empty, display message - PHP / [POST] form如果数组中的任何字段不为空,则显示消息 - PHP / [POST] 表单
【发布时间】:2015-03-27 14:34:14
【问题描述】:

我有一个包含 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.";
}

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

提前致谢!

【问题讨论】:

  • if (!empty($_POST[$field])) ?
  • 检查!empty()

标签: php arrays forms post


【解决方案1】:

我想你想看看 NOT 运算符。

你可以这样写:

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

更多信息参见手册:http://php.net/manual/en/language.operators.logical.php

【讨论】:

    【解决方案2】:

    if中做相反的比较:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 2018-09-01
      • 2010-12-31
      相关资源
      最近更新 更多