0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

(PHP)否定論理演算子「!」はゆるい比較だから気をつけよう

Posted at

先日コードを書いている時、

フラグの値がfalseなら①の処理、それ以外なら②の処理

という条件分岐を実装したいと思い、以下のように書いた。

false か false 以外か
if (!$flg) {
    // ①の処理
} else {
    // ②の処理
}

この$flgにはnullが入ってくることもあり、その場合はelse句の②の処理を実行したかったのだが、結果的には①が実行された。

$flg = null;
if (!$flg) {
    // ①の処理
} else {
    // ②の処理
}

// 結果
// ①が実行される

原因

条件式で使っている「!」が緩い比較になることが原因。
null を false と解釈し、①が実行されてしまった。

なお、nullの他にも以下がfalseと判定されてしまう。

  • 数字 0
  • 文字列 '0'
  • 空配列 []
  • 空文字列 ""
falseになってしまうやつら
$array = [
    0,
    '0',
    null,
    [],
    "",
];

foreach ($array as $bool) {
    if (!$bool) {
        echo 'falseだよ';
    } else {
        echo 'falseじゃないよ';
    }
}

// 結果
// falseだよ
// falseだよ
// falseだよ
// falseだよ
// falseだよ

厳密な比較にすれば解決

厳密な比較
$array = [
    0,
    '0',
    null,
    [],
    "",
];

foreach ($array as $bool) {
    if ($bool === false) {
        echo 'falseだよ';
    } else {
        echo 'falseじゃないよ';
    }
}

// 結果
// falseじゃないよ
// falseじゃないよ
// falseじゃないよ
// falseじゃないよ
// falseじゃないよ

感想

!はコードがスタイリッシュになっていいけどバグりやすいっておもいました。

参考

論理演算子
PHP 型の比較表

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?