Home > Article > Backend Development > null coalescing operator in PHP, PHP null coalescing operator_PHP tutorial
<code class="language-meta">project: blog target: null-coalesce-operator-in-php.md date: 2015-12-30 status: publish tags: - Null Coalesce - PHP categories: - PHP </code>
The null coalescing operator is a good thing. With it, we can easily get a parameter and provide a default value when it is empty. For example, you can use ||
in js:
<code class="language-js">function setSomething(a){ a = a || 'some-default-value'; // ... } </code>
In PHP, unfortunately, PHP's ||
always returns true
or false
, so it cannot be done this way.
PHP7 has only officially added the ??
operator:
<code class="language-php">// 获取user参数的值(如果为空,则用'nobody') $username = $_GET['user'] ?? 'nobody'; // 等价于: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; </code>
It is estimated that PHP7 will take a long time to be used in the production environment. So are there any alternatives to the current PHP5?
According to research, there is a very convenient alternative:
<code class="language-php">// 获取user参数的值(如果为空,则用'nobody') $username = @$_GET['user'] ?: 'nobody'; // 等价于: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; </code>
-- Run this code: https://3v4l.org/aDUW8
I looked at it with my eyes wide open. It was similar to the previous PHP7 example, mainly replacing ??
with ?:
. What the hell is this? In fact, this is the omission pattern of the (expr1) ? (expr2) : (expr3)
expression:
<p>表达式 (expr1) ? (expr2) : (expr3) 在 expr1 求值为 TRUE 时的值为 expr2,在 expr1 求值为 FALSE 时的值为 expr3。<br/> 自 PHP 5.3 起,可以省略三元运算符中间那部分。表达式 expr1 ?: expr3 在 expr1 求值为 TRUE 时返回 expr1,否则返回 expr3。<br/> -- http://php.net/manual/zh/language.operators.comparison.php</p>
Of course, this alternative is not perfect - if there is no $_GET
in 'user'
, there will be an Notice: Undefined index: user
error, so you need to use @
to suppress this error, or turn off E_NOTICE
mistake.