Help us understand the problem. What is going on with this article?

PHP7調査(11)??演算子の新設

More than 3 years have passed since last update.

PHP7で2項演算子「??」が新設されます。左オペランドがnull以外の値であればその値を、そうでなければ右オペランドを返すようなものです。

<?php
var_dump(null ?? false ?? true); // false

これはPHP 5.3で導入されたエルビス演算子「?:」と少し似ています。エルビス演算子は真偽の判断を行いますが、??演算子はnullかどうかの判断を行う点が異なっています。

<?php
var_dump(null ?: false ?: true); // true

それだけでなく、??演算子はisset()と同様に未定義値をチェックしてもエラーになりません。これは非常に大きな違いで、??演算子があれば今までのisset()地獄から解放されるかもしれません。

<?php
var_dump($arr["foo"] ?: "bar"); // 未定義だとUndefined variableかUndefined indexで怒られちゃう
var_dump(isset($arr["foo"]) ? $arr["foo"] : "bar"); // 結局こう書いてたよね…

var_dump($arr["foo"] ?? "bar"); // PHP7ではこれで動く!

参照

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした