: This article mainly introduces the null merge operator in PHP. if you are interested in the PHP Tutorial, refer to it. The null merge operator is a good thing. with it, we can easily obtain a parameter and provide a default value when it is null. For example, | can be used in js:
function setSomething(a){ a = a || 'some-default-value'; // ...}
In PHP, it is a pity that PHP's | always returns true or false, so this cannot be done.
PHP 7 was officially added ?? This operator:
// Obtain the value of the user parameter (if it is null, use 'nobody') $ username = $ _ GET ['user']? 'Nobody'; // equivalent to: $ username = isset ($ _ GET ['user'])? $ _ GET ['user']: 'Nobody ';
PHP7 is estimated to be used in the production environment for a long time. Is there any alternative solution in the current PHP5?
According to research, there is a very convenient alternative:
// Obtain the value of the user parameter (if it is null, use 'nobody') $ username = @ $ _ GET ['user']? : 'Nobody'; // equivalent to: $ username = isset ($ _ GET ['user'])? $ _ GET ['user']: 'Nobody ';
-- Run this code: https://3v4l.org/aDUW8
With a Wide Eye, the PHP7 example is similar to the above ?? To? :. What is this? Actually this is (expr1 )? (Expr2): (expr3) the omitted mode of the expression:
Expression (expr1 )? (Expr2): (expr3) when the value of expr1 is TRUE, the value is expr2, and when the value of expr1 is FALSE, the value is expr3.
From PHP 5.3, the portion in the middle of the ternary operator can be omitted. Expression expr1? : Expr3 returns expr1 when the value of expr1 is TRUE; otherwise, expr3 is returned.
Http://php.net/manual/zh/language.operators.comparison.php
Of course, this alternative solution is not perfect-if $ _ GET does not contain 'user', there will be a Notice: Undefined index: user error, so you need to use @ to suppress this error, or the error of disabling E_NOTICE.
Ps: PHP7 null merge operator farewell to isset ()
Previous writing
$info = isset($_GET['email']) ? $_GET['email'] : ‘noemail';
Now you can simply write it like this.
$info = $_GET['email'] ?? noemail;
You can also use this connection.
$info = $_GET['email'] ?? $_POST['email'] ?? ‘noemail';
The preceding section describes the null merge operators in PHP, including some content. I hope you will be helpful to anyone interested in the PHP Tutorial.