首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP 检测变量是否为空

PHP 检测变量是否为空

作者头像
德顺
发布2019-11-13 10:30:41
7.2K0
发布2019-11-13 10:30:41
举报
文章被收录于专栏:前端资源前端资源
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)) { ... }

原文链接:PHP 检测变量是否为空

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档