在php中判断变量为空我们有很多种方法,php为我们提供了empty,isset,var == null,is_null等等函数来进行变量判断,下面我来给大家分享这些方法的使用方法.empty() 与 isset() 的一个简单比较.
实例代码如下:
<?php $var = 0; // 结果为 true,因为 $var 为空 // 结果为 true,因为 $var =0 if (emptyempty($var)) { echo '$var is either 0 or not set at all'; } //结果为false, 因为$var已经设置了 if (!isset($var)) { echo '$var is not set at all'; } ?>
上面的empty与isset判断为没有任何属性的对象都将被认为是空.var == null
功能:判断变量是否为"空"
说明:值为 0 或 false 或 空字符串"" 或 null的变量、空数组、都将判断为 null
注意:与empty的显著不同就是:变量未初始化时 var == null 将会报错.
实例代码如下:
$a = 0; $b = array(); if ($a == null) echo '$a 为空' . ""; if ($b == null) echo '$b 为空' . ""; if ($c == null) echo '$b 为空' . ""; // 显示结果为 // $a 为空 // $b 为空 // Undefined variable: c
is_null实例代码如下:
$a = null; $b = false; if (is_null($a)) echo '$a 为NULL' . ""; if (is_null($b)) echo '$b 为NULL' . ""; if (is_null($c)) echo '$c 为NULL' . ""; // 显示结果为 // $a 为NULL // Undefined variable: c
变量==0 或 变量===0
实例代码如下:
$a ===0 $a ==="" $a ==0 等于 $a ==""
在php url传参数时php页面的 URL 尾部参数出现 id=0 时(比如:test.php?id=0),试比较:
实例代码如下:
if(emptyempty($id)) $id=1; // 若 id=0 ,id 也会为1 if(!isset($id)) $id=1; // 若 id=0 ,id 不会为1
可分开运行以下代码检测上述推断:
if(emptyempty($id)) $id=1; print $id; // 得到 1 if(!isset($id)) $id=1; print $id; //得到 0
总结
在php中NULL与空是两种不同的概念,isset 主要用来判断变量是否被初始化过empty 可以将值为 "假"、"空"、"0"、"NULL"、"未初始化" 的变量都判断为TRUE
is_null 仅把值为 "NULL" 的变量判断为TRUE var == null 把值为 "假"、"空"、"0"、"NULL" 的变量都判断为TRUE var === null 仅把值为 "NULL" 的变量判断为TRUE
其它一些可能用到php变量判断的函数
isset($ var) : //变量是不是已经声明 empty($ var): //变量是不是为空 defined($ var): //常量是不是已经定义 define() is_array($ var): //检验测定变量是不是是数组 is_null($ var): //检验测定变量是不是为 null
本文地址:
转载随意,但请附上文章地址:-)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool