开发者

what difference between NULL, blank and empty in php?

开发者 https://www.devze.com 2022-12-23 08:49 出处:网络
i have one form which havesome input box and some select box. i want to apply that nothing can be empty or blank before further activity,

i have one form which have some input box and some select box. i want to apply that nothing can be empty or blank before further activity, so i use below condition

foreach($_POST as $k=>$v)
{
    if($v=='' || $v==NULL || empty($v))
    开发者_Go百科{
        $_SESSION['errMsg']=' Please fill all the fields properly';
                    header("location:somepage.php");
                    exit;
    }
     }

now my question is:

above if is useful or not?

if not then which condition is enough to prevent blank entry $v=='' or $v==NULL or empty($v) or i have to use all of these conditions?

Thanks in advance


empty() should take care of all those.

From the manual:

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

And the very handy Type-Comparison Table


Mike already described when emtpy() evaluates to true.
But note this:

  • Every value in $_POST is a string anyway, so comparing it to NULL is unnecessary.
  • If a field is allowed to have the value 0, you have to treat it differently as empty() will return true for this value too!


PHP function empty() checks for everything you asked for. You also might consider form fields being empty, if they contain only whitespaces or line breaks. Avoid this by adding trim().

foreach($_POST as $k=>$v) {
    if (empty(trim($v))) {
        //...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消