Home > Backend Development > PHP Tutorial > Note 015 Special usage of ?: in PHP

Note 015 Special usage of ?: in PHP

黄舟
Release: 2023-03-04 09:16:01
Original
1497 people have browsed it

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)!


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template