如果两个条件为真,那么php echo之前有一个问题,大多数人使用语句if(!empty($variable)){}
来检查变量是否为空,而我回答if($variable != ''){}
。我的问题是,为什么他们中的大多数人都用if(!empty($variable)){}
回答,if($variable != ''){}
期望的可读性有什么区别?可读性是我目前看到的唯一区别。
谢谢阿特诺
阅读手册
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
* "" (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)
* var $var; (a variable declared, but without a value in a class)
注意::
请注意,如果"0"(零作为字符串)、0(零作为整数)和 -0(减零作为整数)返回 true,"-0"(减零作为字符串(是的,我已经有一些客户将 -0 写入表单字段))返回 false。在使用 empty() 函数测试变量之前,您需要强制转换变量:
<?php
$var = "-0";
echo empty($var); // returns false
$var = (int) $var; // casts $var as an integer
echo empty($vat); // returns true
?>
empty 也认为变量是空的,如果它们是 0-Integer、NULL、FALSE、一个空数组(查看返回值)。您只检查它是否不是空字符串。如果变量设置为(布尔值)FALSE,则检查将返回true。