54
38

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

【PHP】: isset, is_null, if($var), empty 比較一覧

Last updated at Posted at 2020-10-25

比較一覧

|値 or 要素|型||isset |is_null |empty |if($var)||!empty
---|---|---|---|:-:|:-:|:-:|:-:|---|:-:|
1|$var|未定義
(null)||false|error
(true)|true|error
(false)||false
2|$var = NULL|null||false|true|true|false||false
3|$var = "";|string||true|false|true|false||false
4|$var = 0;|int||true|false|true|false||false
5|$var = "0";|string||true|false|true|false||false
6|$var = 1|int||true|false|false|true||true
7|$var = "1";|string||true|false|false|true||true
8|$var = array()|array||true|false|true|false||false
9|$var = array(1)|array||true|false|false|true||true

解説1

isset(公式)
empty(公式)
empty($var)!isset($var) || $var == false と同義(公式より)
!empty($var)isset($var) && $var == true と同義。

!isset()をis_nullの代わりに使うほうがセーフティ。
!emptynullチェックif($var)ダブルチェック
青字部分の$var=0$var="0"に気をつけてください。

まとめ

isset未定義を含む、nullチェック
empty未定義を含む、値がないときのチェック。
if($var)未定義チェックなしの値があるときのチェック。
!empty未定義チェックありの値があるときのチェック。
青字の判定部分は__かなり微妙__で、数値的な0文字列の"0"ないものと判定されます。

クラス内変数

|値 or 要素|型||isset |is_null |empty |if($var)||!empty
---|---|---|---|:-:|:-:|:-:|:-:|---|:-:|
1|$var|未定義
(null)||false|true|true|false||false
*|以下同上

getter 比較一覧

|値 or 要素|型||isset |is_null |empty |if($var)||!empty
---|---|---|---|:-:|:-:|:-:|:-:|---|:-:|
1|$var|未定義
(null)||false|true|true|false||false
2|$var = NULL|null||false|true|true|false||false
3|$var = "";|string||false|false|true|false||false
4|$var = 0;|int||false|false|true|false||false
5|$var = "0";|int||false|false|true|false||false
6|$var = 1;|int||false|false|true|true||false
7|$var = "1";|int||false|false|true|true||false
8|$var = array()|array||false|false|true|false||false
9|$var = array(1)|array||false|false|true|true||false

解説2

getterでは打って変わって、!is_nullif($var)が幸せになれそうです。
issetは全く機能しません。!is_nullを使用しましょう。
empty中身のある配列で挙動がおかしいので、素直にif($var)がよさそうです。
こちらも青字の$var=0$var="0"$var=array(1)には気を付けてください。

公式の比較表

PHP 型の比較表

LGTMお願いします!
ストックのついでにお願いします!
モチベーションがあがります!

54
38
9

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
54
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?