PHP检查是否为空字段

PHP检查是否为空字段

本文介绍了PHP检查是否为空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个约有10个字段的注册表单,在处理之前都必须填写它们,因此,如果我提出的支票试图避免所有这些,这是一个好方法吗?

I have a sign up form with about 10 fields and they are all required to be filled in before processing, so trying to avoid all those if checks I came up with this, is this a good method?

foreach($list as $items) {
   if(empty($items)) {
      $error[] = "All fields are required.";
      break;
   }
}

还是应该让if(empty($ field_1)||空($ field_2)等.然后输出错误?

or should I make if(empty($field_1) || empty($field_2) etc.. then output the error?

推荐答案

假设您的数据来自 $ _ GET $ _ POST ,则所有数据字段均为字符串.这意味着您应该能够在单个函数调用中进行检查:

Assuming that your data is coming from $_GET or $_POST, all data fields will be strings. This means that you should be able to do the check in a single function call:

if (in_array('', $list, TRUE)) {
  $error[] = "All fields are required.";
}

这将查找完全等于空字符串的字符串.如果您想使比较松散(或多或少与 empty()所做的检查相同),只需删除最后的 TRUE .

This looks for strings which are exactly equal to an empty string. If you want to make the comparisons loose (more or less identical to the check that empty() does) just remove the final TRUE.

编辑考虑一下,您不需要严格的比较.我这样做是为了允许'0'的合法字段值( empty()不允许),但是由于>'0'!=''.

EDIT Thinking about it, you don't need the strict comparison. I did this to allow for a legitimate field value of '0' (which empty() would not allow) but this will also be permitted with loose comparisons, since '0' != ''.

另一项编辑如果要检查字符串的长度是否大于2,则必须循环:

ANOTHER EDIT If you want to check that the length of the sting is greater than two, you will have to loop:

foreach ($list as $item) {
  if (strlen($item) < 2) {
    $error[] = "All fields are required.";
    break;
  }
}

这还将清除 0 ",前提是您的意思是不允许将值设为 0 ".如果您还想禁止 '00'(或任何其他导致 0 的字符串),则可以将 if 子句更改为此:

This will also "clear out 0" assuming that by this you mean "not allow a value to be 0". If you also want to disallow '00' (or any other string that results in 0) you can change the if clause to this:

if (strlen($item) < 2 || (!(int) $item)) {

这篇关于PHP检查是否为空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:45