Home >Backend Development >PHP Tutorial >Note 015 Special usage of ?: in PHP
Programmers who have a certain understanding of PHP will not feel unfamiliar when they see ?:. It is a very awesome grammatical structure: the ternary operator.
The usage of the ternary operator is as follows:
(expr1) ? (expr2) : (expr3)
When expr1 is true, the value of expr2 will be returned , when expr1 is false, the value of expr3 will be returned.
However, starting from PHP 5.3 version, the ternary operator is no longer limited to the above operation method. He can also use it like this:
(expr1) ?: (expr2)
, which means connecting ?: together. If this usage is adopted, when expr1 is true, expr1 itself will be returned, and when expr1 is false, the value of expr2 will be returned.
This is a very useful way of writing, so Hy369 can’t wait to write this in his PHP blog so that all friends can know it!
Special reminder: Note that the ternary operator is a statement, so its evaluation is not a variable, but the result of the statement. This is important if you want to return a variable by reference. The statement return $var == 369 ? $a : $b; in a function that returns by reference will not work, and a future version of PHP will issue a warning about this.
The above is the content of the special usage of ?: in Note 015 PHP. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!