18
12

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.

PHP/JavaScriptの真偽と型

Posted at

PHPの真偽や型について、ちゃんと分かっていなかったので、
JavaScriptとともにまとめてみました。

まとめ

様々な値をif文で評価した結果を表にしました。
型についてはPHPがvar_dump、JavaScriptではtypeofに基づく情報です。

入力値 PHP JavaScript 備考
TRUE TRUE (bool) TRUE (boolean)
FALSE FALSE (bool) FALSE (boolean)
-1 TRUE (int) TRUE (number)
0 FALSE (int) FALSE (number)
1 TRUE (int) TRUE (number)
-0.1 TRUE (float) TRUE (number)
0.0 FALSE (float) FALSE (number)
0.1 TRUE (float) TRUE (number)
NaN --- FALSE (number) JavaScriptのみ
Infinity --- TRUE (number) JavaScriptのみ
文字列 'a' TRUE (string) TRUE (string)
空文字列 '' FALSE (string) FALSE (string)
文字列のゼロ '0' FALSE (string) TRUE (string) 結果が違う
NULL FALSE (NULL) FALSE (object)
undefined --- FALSE (undefined) JavaScriptのみ
空の配列
PHP: array()
JavaScript: []
FALSE (array) TRUE (object) 結果が違う
空でない配列
PHP: array(0)
JavaScript: [0]
TRUE (array) TRUE (object)
空のオブジェクト
PHP: new stdClass()
JavaScript: {}
TRUE (object) TRUE (object)

PHPでは文字列のゼロや空の配列がFALSEになるんですね。
JavaScriptを書くことの方が多いので、このあたりは気をつけようと思います。

18
12
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
18
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?