PHP 检测变量是否为空
PHP 中以下值得计算结果为 false:
关键字 | 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 \r\n"; } else { echo "string \"0\" is false \r\n"; // 输出:string "0" is false } if(empty($number)) { echo "string \"0\" is false \r\n"; // 输出:string "0" is false } else { echo "string \"0\" is not false \r\n"; }
空数组:
<?php $arr= array(); if($arr) { echo 'array $arr is not false'."\r\n"; } else { echo 'array $arr is false'."\r\n"; // 输出:array $arr is false } if(empty($arr)) { echo 'array $arr is false'."\r\n"; // 输出:array $arr is false } else { echo 'array $arr is not false'."\r\n"; }
空对象在 PHP 5 以上版本中计算结果不为 false:
$obj=(object)array(); if($obj) { echo '$obj is not false'."\r\n"; // 输出:$obj is not false } else { echo '$obj is false'."\r\n"; } if(empty($obj)) { echo '$obj is false'."\r\n"; } else { echo '$obj is not false'."\r\n"; // 输出:$obj is not false }
注意:字符串"0.0"、字符串"00"、包括一个空格字符的字符串" "、字符串"false" 、整型 -1 都不为 false:
<?php $number = "0.0"; if($number) { echo "string \"0.0\" is not false \r\n"; // 输出:string "0.0" is not false } else { echo "string \"0.0\" is false \r\n"; } if(empty($number)) { echo "string \"0.0\" is false \r\n"; } else { echo "string \"0.0\" is not false \r\n"; // 输出:string "0.0" is not false }
正确地检查一个变量是否为空应该使用:
<?php if (empty($var)) { ... }