1
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 初心者向け】「$foo ?? null」は「$foo」ではないし、「is_null($foo) ? null : $foo」でもない

Posted at

実例

<?php

// $foo = 10;
$bar = 20;

print(json_encode($foo ?? null));  // → エラーにならない
print("\n");

print(json_encode($foo));  // → 警告 (Laravel では処理が停止)
print("\n");

print(json_encode(is_null($foo) ? null : $foo));  // → 警告 (Laravel では処理が停止)
print("\n");
$ php isnull.php
null
PHP Warning:  Undefined variable $foo in /home/yuinore/projects/phpscript/isnull.php on line 9
null
PHP Warning:  Undefined variable $foo in /home/yuinore/projects/phpscript/isnull.php on line 12
null

別の例(配列)

<?php

$foo = [
    "hoge" => 10,
    "fuga" => 30,
    // "piyo" => 50,
];
$bar = 20;

print(json_encode($foo["piyo"] ?? null));  // → エラーにならない
print("\n");

print(json_encode($foo["piyo"]));  // → 警告 (Laravel では処理が停止)
print("\n");

print(json_encode(is_null($foo["piyo"]) ? null : $foo["piyo"]));  // → 警告 (Laravel では処理が停止)
print("\n");
$ php isnull2.php
null
PHP Warning:  Undefined array key "piyo" in /home/yuinore/projects/phpscript/isnull2.php on line 13
null
PHP Warning:  Undefined array key "piyo" in /home/yuinore/projects/phpscript/isnull2.php on line 16
null

解説

PHP の null 合体演算子 ?? においては、左側の値が存在しない場合でも notice や warning が発生せず、 isset() の判定条件と同じ挙動になります。(解説終わり)

print(json_encode(isset($foo) ? $foo : null));  // → エラーにならない

ですので、 ?? null は冗長だと勘違いして消してしまわないようにしましょう。

式 (expr1) ?? (expr2) は、 expr1 が null である場合は expr2 と評価され、それ以外の場合は expr1 と評価されます。
この演算子は、左側の値が存在しない場合でも notice や warning が発生しません。 isset() と同じ挙動です。 これは、配列のキーを扱う場合に便利です。

備考

error_reporting の設定によっては警告が発生しない場合があります。

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