7
4

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 5 years have passed since last update.

値をboolで返すには ()だけでは変換されない【5パターン】

7
Last updated at Posted at 2015-12-09

ifのように()で囲めば暗黙のtrueとの比較でboolが得られると勘違いしていたので戒めとしてメモる。

($hoge > $huga)boolになるのは、あくまで比較演算子での式がboolを返すから。

コードパターン

ifでできる書き方

if ($a == true) {}
if ($a) {} // trueとのゆるい比較で上と同義


簡略化できるパターン

if ($result == $hoge) {
    $return = true;
} else {
    $return = false:
}

return $result;

簡略化

return ($result == $hoge);

同様にはできない簡略化パターン

if ($result) {
    $return = true;
} else {
    $return = false:
}

return $result;


失敗パターン

return ($result); // $resultの値そのままが返る
// そもそもこれでは省略可能なreturnの()を省略していないだけでは?
var_dump(($result)); // これもboolにはならない

変換方法

boolへの変換(ワンライナー)

(bool) $result         // キャスト (boolean)でも可
boolval($result)       // 関数。5.5以上
($result == true)      // 比較結果
!!$result              // JSなどでたまに見る。反転時にboolになり、その反転で正しいbool値取得
$result ? true : false // 三項演算子(デバッグでboolのstring変換とかで似たものをよく使う)

($result && true)      // 論理積。使い道なし…と思う(自動キャストされてる?)

他にもあるかな?


PHPに限りませんが、キャストと関数が用意されているとどちらを使えばいいかちょっと迷いますね。

参考記事


今更調べたらif ($hoge)の資料ってあんまり出ないですね。
PHP逆引きレシピには書いてあったのですが…
while ($hoge)とかもよく使うんですが、値のみを式として評価ってどっからきてるんだ…?

7
4
3

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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?