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?

php:(bool) の挙動

Posted at

曖昧な片付けで悩まされるphp。
今回は表題のキャストで自分にとっての予期せぬ挙動を紹介します。

  1. string型の変数にコマンラインの引数やクエリパラメータで受けとった値の 'true', 'false' が格納されている。
  2. 予想
    • $flg = 'true'の時
      • (bool) $flgは真偽値trueとなる。
    • $flg = 'false'の時
      • (bool) $flgは真偽値falseとなる。
  3. 結果
    1. /var/www/html # php -r 'echo (bool) "true" ? "真" : "偽", PHP_EOL;'
      →真
    2. php -r 'echo (bool) "false" ? "真" : "偽", PHP_EOL;'
      →真
  4. 3の結果になるのはphpはざっくり
    値があれば真、それ以外(0、null、空文字)と判定する からです。
  5. なので下記は偽となります。
  • php -r 'echo (bool) "" ? "真" : "偽", PHP_EOL;'
  • php -r 'echo (bool) 0 ? "真" : "偽", PHP_EOL;'
  • php -r 'echo (bool) null ? "真" : "偽", PHP_EOL;'
  • php -r 'echo (bool) [] ? "真" : "偽", PHP_EOL;'
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?