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, in js, you can use || to do:
function setSomething(a){ a = a || 'some-default-value'; // ... }
. But in PHP, unfortunately, PHP's || always returns true or false, so you can't do it this way.
PHP7 has just officially added this operator:
// 获取user参数的值(如果为空,则用'nobody') $username = $_GET['user'] ?? 'nobody'; // 等价于: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
It is estimated that PHP7 will take a long time to be used in the production environment. So are there any alternatives in the current PHP5?
According to research, there is a very convenient alternative:
// 获取user参数的值(如果为空,则用'nobody') $username = @$_GET['user'] ?: 'nobody'; // 等价于: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
-- Run this code: https://3v4l.org/aDUW8
Look at it with wide eyes, it is similar to the previous PHP7 example, The main thing is to replace ?? with ?:. What the hell is this? In fact, this is the omission pattern of (expr1) ? (expr2) : (expr3) expression:
Expression (expr1) ? (expr2) : (expr3) When expr1 evaluates to TRUE, the value is expr2, and when expr1 evaluates to The value when FALSE is expr3.
Since PHP 5.3, you can omit the middle part of the ternary operator. The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE and expr3 otherwise.
-- http://php.net/manual/zh/language.operators.comparison.php
Of course, this alternative is not perfect - if there is no 'user' in $_GET, there will be a Notice : Undefined index: user error, so you need to use @ to suppress this error, or turn off the E_NOTICE error.
ps: PHP7 null coalescing operator Say goodbye to isset()
the previous way of writing
$info = isset($_GET['email']) ? $_GET['email'] : ‘noemail';
Now you can just write it like this
$info = $_GET['email'] ?? noemail;
You can also write it in conjunction like this
$info = $_GET['email'] ?? $_POST['email'] ?? ‘noemail';
The above has introduced a detailed explanation of the null coalescing operator in PHP, including relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.