鍍金池/ 教程/ PHP/ 檢測一個值是否為 null 或 false
驗證郵件地址
自動加載類
PHP 與 MySQL
緩存 PHP opcode
檢測一個值是否為 null 或 false
PHP 標簽
從性能角度來看單引號和雙引號
發(fā)送郵件
處理日期和時間
define() vs. const
配置 Web 服務(wù)器提供 PHP 服務(wù)
PHP 與 UTF-8
我們在使用哪個版本的 PHP?
凈化 HTML 輸入和輸出
PHP 與正則表達式
存儲密碼
PHP 與 Memcached

檢測一個值是否為 null 或 false

使用 === 操作符來檢測 null 和布爾 false 值。

PHP 寬松的類型系統(tǒng)提供了許多不同的方法來檢測一個變量的值。 然而這也造成了很多問題。 使用 == 來檢測一個值是否為 null 或 false,如果該值實際上是一個空字符串或 0,也會誤報為 false。 isset 是檢測一個變量是否有值, 而不是檢測該值是否為 null 或 false,因此在這里使用是不恰當?shù)摹?/p>

is_null() 函數(shù)能準確地檢測一個值是否為 null, is_bool 可以檢測一個值是否是布爾值(比如 false), 但存在一個更好的選擇:=== 操作符。=== 檢測兩個值是否同一, 這不同于 PHP 寬松類型世界里的 相等。它也比 is_null() 和 is_bool() 要快一些,并且有些人認為這比使用函數(shù)來做比較更干凈些。

示例

<?php
$x = 0;
$y = null;

// Is $x null?
if($x == null)
    print('Oops! $x is 0, not null!');

// Is $y null?
if(is_null($y))
    print('Great, but could be faster.');

if($y === null)
    print('Perfect!');

// Does the string abc contain the character a?
if(strpos('abc', 'a'))
    // GOTCHA!  strpos returns 0, indicating it wishes to return the position of the first character.
    // But PHP interpretes 0 as false, so we never reach this print statement!
    print('Found it!'); 

//Solution: use !== (the opposite of ===) to see if strpos() returns 0, or boolean false.   
if(strpos('abc', 'a') !== false)
    print('Found it for real this time!');
?>

陷阱

  • 測試一個返回 0 或布爾 false 的函數(shù)的返回值時,如 strpos(),始終使用 === 和!==,否則你就會碰到問題。

進一步閱讀

上一篇:PHP 標簽下一篇:驗證郵件地址