5
1

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】nullの動き方27パターンまとめ

Last updated at Posted at 2019-01-15

はじめに

PHPのnullの動き方が気になったのでまとめます。随時追記していこうと思います。
こういうパターンもあるよ!というものがあれば教えてください!
今回はLaravelのdd関数(dump and die)を使っていきます。

null


dd(null);
// -> null

キャスト


dd(int null);
// -> 0

dd(string null);
// -> ""

dd(array null);
// -> []

dd(bool null);
// -> false

dd(float null);
// -> 0.0

dd(object null);
// -> {#1432}

四則演算


dd(null + null);
// -> 0;

dd(null - null);
// -> 0;

dd(null * null);
// -> 0;

dd(null / null);
// -> ErrorException Division by zero

変数操作関数


dd(empty(null));
// -> true;

dd(gettype(null));
// -> 'NULL';

dd(intval(null));
// -> 0;

dd(is_array(null));
// -> false

dd(is_bool(null));
// -> false

dd(is_int(null));
// -> false

dd(is_null(null));
// -> true

dd(isset(null));
// -> FatalErrorException Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

$a = null; //直接null入れるとエラー吐くため
dd(isset(null));
// -> false

dd(strval(null));
// -> ''

その他

dd(null == 0);
// -> true

dd(null === 0);
// -> false

dd(null == '');
// -> true

dd(null === '');
// -> false

dd(date(null));
//-> ''

$a = password_hash(null, PASSWORD_BCRYPT);
dd($a);
// -> '$2y$10$qpzDi1Bx8.QKBlZ3EX8yBOjXehZqLV4Zs/XwESf3ZvLNRC3vczMsi'

最後に

型判定などはよく使うのでnullに気をつけたいですね。

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?