LoginSignup
0
0

More than 3 years have passed since last update.

PHP if, isset, emptyの真偽の判定について if()

Last updated at Posted at 2020-04-02

条件分岐の基本的なところでつまづいたので、if,isset,emptyの挙動について簡単にまとめてみます。

配列$arrayをif, isset, empty それぞれで出力してみました。
$array = [0, '0', 10, false, true, null, '', [] ];


foreach($array as $val){
  if($val){echo "truthy";}
  if(!$val){echo "falsy";}
  echo "\n";
}

foreach($array as $val){
  if(isset($val)){echo "truthy";}
  if(!isset($val)){echo "falsy";}
  echo "\n";
}

foreach($array as $val){
  if(empty($val)){echo "truthy";}
  if(!empty($val)){echo "falsy";}
  echo "\n";
} 

結果
$array = [
  0,            //[if]→falsy      [isset]→truthy      [empty]→truthy
  '0',          //[if]→falsy      [isset]→truthy      [empty]→truthy
  10,           //[if]→truthy     [isset]→truthy      [empty]→falsy
  false,        //[if]→falsy      [isset]→truthy      [empty]→truthy
  true,         //[if]→truthy     [isset]→truthy      [empty]→falsy
  null,         //[if]→falsy      [isset]→falsy       [empty]→truthy
  '' ,          //[if]→falsy      [isset]→truthy      [empty]→truthy
  []            //[if]→falsy      [isset]→truthy      [empty]→truthy
];

まとめ

この結果から、例えばif文で「何かしらの数値(0や'0'を含む)が入った状態を"真"としたい場合」などのときは、(==, !=, ===, !==)を使って比較してあげる必要がある、といったところが注意点でしょうか。

基礎的な部分ですが見落としがちで、気が付きにくいエラーの原因にもなりそうなので、簡単にまとめてみました。

他にも注意点や内容のご指摘あればご教授していただけると喜びます。
以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0