PHP中區分null和false的方法

echo json_encode(0)."<br/>";     //輸出"0"

echo json_encode(null)."<br/>";    //輸出"null"

echo json_encode(false)."<br/>";    //輸出"false"

//被json_encode轉碼後,類型就是string
//作判斷就得用以下例子:
if(json_encode(null) =="null"){
    echo 1;
}else{
    echo 2;
}
//輸出1

區分    null和    false意義很大,由於在數據庫交互中,如select,查詢結果是空則返回 null, 而出錯則返回 false。php

區分了  null  和  false,才能夠更加好地支持   事務數據庫

 

Thinkphp的query方法數據庫交互的錯誤判斷:json

$model =new Model();
$order ="select * from asd where seatNm=1";
$res =$model->query($order);

if(json_encode($res) !="false" && $res[0] ==null){    //結果集爲空
    echo 123;
}else if(json_encode($res) =="false"){    //查詢出錯
    echo 789;
}else{     //返回非空結果集
    echo 456;
}

ps:我用的是tp3.1,不知道3.2是否是有更好的判斷機制出現code

 

補充:還可以使用恆等於來作判斷:===事務

$paramI   =null;
$paramII  =false;
$paramIII =0;
if($paramI ===false){
    exit("fail to judge null");
}else {
    exit(json_encode($paramI));
}
//輸出null
if($paramII ===0){
    exit("fail to judge false");
}else {
    exit(json_encode($paramII));
}
if($paramI ===null){
    exit("fail to judge 0");
}else {
    exit(json_encode($paramIII));
}
相關文章
相關標籤/搜索