PHP 检测变量是否为空
- 2019 年 11 月 13 日
- 筆記
关键字 |
boolean |
false |
---|---|---|
整型 |
integer |
0 |
浮点型 |
double |
0.0 |
字符串 |
string |
"" |
字符串 |
string |
"0" |
数组 |
array |
array() |
对象 |
object |
空对象 php<5 |
null |
null |
NULL |
例如 字符串"0":
<?php $number = "0"; if($number) { echo "string "0" is not false rn"; } else { echo "string "0" is false rn"; // 输出:string "0" is false } if(empty($number)) { echo "string "0" is false rn"; // 输出:string "0" is false } else { echo "string "0" is not false rn"; }
空数组:
<?php $arr= array(); if($arr) { echo 'array $arr is not false'."rn"; } else { echo 'array $arr is false'."rn"; // 输出:array $arr is false } if(empty($arr)) { echo 'array $arr is false'."rn"; // 输出:array $arr is false } else { echo 'array $arr is not false'."rn"; }
空对象在 PHP 5 以上版本中计算结果不为 false:
$obj=(object)array(); if($obj) { echo '$obj is not false'."rn"; // 输出:$obj is not false } else { echo '$obj is false'."rn"; } if(empty($obj)) { echo '$obj is false'."rn"; } else { echo '$obj is not false'."rn"; // 输出:$obj is not false }
注意:字符串"0.0"、字符串"00"、包括一个空格字符的字符串" "、字符串"false" 、整型 -1 都不为 false:
<?php $number = "0.0"; if($number) { echo "string "0.0" is not false rn"; // 输出:string "0.0" is not false } else { echo "string "0.0" is false rn"; } if(empty($number)) { echo "string "0.0" is false rn"; } else { echo "string "0.0" is not false rn"; // 输出:string "0.0" is not false }
正确地检查一个变量是否为空应该使用:
<?php if (empty($var)) { ... }
原文链接:PHP 检测变量是否为空