PHP check if False or Null

早过忘川 提交于 2019-12-05 12:05:06

问题


I also get confused how to check if a variable is false/null when returned from a function.

When to use empty() and when to use isset() to check the condition ?


回答1:


For returns from functions, you use neither isset nor empty, since those only work on variables and are simply there to test for possibly non-existing variables without triggering errors.

For function returns checking for the existence of variables is pointless, so just do:

if (!my_function()) {
    // function returned a falsey value
}

To read about this in more detail, see The Definitive Guide To PHP's isset And empty.




回答2:


Checking variable ( a few examples )

if(is_null($x) === true) // null
if($x === null) // null
if($x === false)
if(isset($x) === false) // variable undefined or null
if(empty($x) === true) // check if variable is empty (length of 0)



回答3:


Isset() checks if a variable has a value including ( False , 0 , or Empty string) , But not NULL. Returns TRUE if var exists; FALSE otherwise.

On the other hand the empty() function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value.




回答4:


ISSET checks the variable to see if it has been set, in other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a " ", 0, "0", or FALSE are set, and therefore are TRUE for ISSET.

EMPTY checks to see if a variable is empty. Empty is interpreted as: " " (an empty string), 0 (0 as an integer), 0.0 (0 as a float), "0" (0 as a string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class.




回答5:


isset — Determine if a variable is set and is not NULL

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE

empty — Determine whether a variable is empty

<?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
  echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
  echo '$var is set even though it is empty';
}
?>



回答6:


  • check false: if ($v === false)
  • check null: if (is_null($v))

empty() is an evil.It is slow,and when $v queals false,0,'0',array(),'',it will return true.if you need this kind of checking,you can use if ($v).



来源:https://stackoverflow.com/questions/11464714/php-check-if-false-or-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!