up
down
Close
架站盒子
Web Development Box
 

PHP isset()、empty()、null() 的差別

│ 1594 Views │ PHP
PHP isset()、empty()、null() 的差別
PHP isset()、empty()、null() 的差別

在判斷變數是否為空值或是否存在的時候,最常看到的就是isset()empty()is_null(),千萬別任意使用,否則會發生與預期不符的結果,而它們之間有何差異呢?以下做簡單介紹。

isset()

issset()顧名思義就是已設置,因此指的是變數是否存在,如果有設置變數,即使是空值也會返回true

empty()

empty()顧名思義就是空的,因此指的是變數的值是否為空,如果有設置變數,且裡面是空值,包含null0"",都會返回true

is_null()

is_null()顧名思義就是無效的、不存在的、無值,因此指的是變數的值是否無效、不存在,如果有設置變數,且裡面是無效的(var $x)、不存在的值(undefinednull),則返回true

empty()和is_null()差異

empty()is_null()最大的不同在於前者設0""時,empty()會返回trueis_null則返回false,因為對is_null來說它是有效的值。

綜合比較

以下圖表出自PHP官網:PHP type comparison tables
php isset empty is_null 差異
圖片出處:PHP type comparison tables
php isset empty is_null 差異
圖片出處:PHP type comparison tables
php isset empty is_null 差異
圖片出處:PHP type comparison tables

延伸閱讀

本文是否對您有幫助?