スポンサーリンク

【PHP】issetの落とし穴

 

データの存在チェックのときにissetを使ってハマってしまったのでメモしときます

以下の配列に対してcomputerというkeyがあるかを探します

$category =

array(9) {
[“”]=>
null
[“domestic”]=>
null
[“world”]=>
null
[“economy”]=>
null
[“entertainment”]=>
null
[“sports”]=>
null
[“computer”]=>
null
[“science”]=>
null
[“local”]=>
null
}

 

チェックするやり方として

isset($category[‘computer’]);

array_key_exists(‘computer’,$category);

を使おうとしますが

これissetだとfalseが返ってきます

なぜならisset は「未定義変数 且つ NULL」の場合に FALSE を返すからです

なのでissetを使うなら以下のようにnullではなく空文字を入れるようにする

 

array(9) {
[“”]=>
string(0) “”
[“domestic”]=>
string(0) “”
[“world”]=>
string(0) “”
[“economy”]=>
string(0) “”
[“entertainment”]=>
string(0) “”
[“sports”]=>
string(0) “”
[“computer”]=>
string(0) “”
[“science”]=>
string(0) “”
[“local”]=>
string(0) “”
}

 

 

 

 

 

 

コメント

タイトルとURLをコピーしました