Detailed explanation of php ternary operator

怪我咯
Release: 2023-03-10 21:40:01
Original
4908 people have browsed it

The

ternary operator operator in php is also called the ternary operator. In fact, I often call it the question mark operator. In fact, you can do this with the ternary operator. Simple conditional judgment function can be realized. Now let me introduce some examples of ternary operators to you.

The function of the ternary operator is consistent with the "if...else" process statement. It is written in one line, with concise code and high execution efficiency. Proper use of the ternary operator in PHP programs can make scripts more concise and efficient. The syntax of the code is as follows:

(expr1)?(expr2):(expr3); //表达式1?表达式2:表达式3
Copy after login

Explanation: If the condition "expr1" is true, execute the statement "expr2", otherwise execute "expr3".

<?PHP
$a=10; $b=20;
$c=$a>$b?($a-$b):($a+$b);
//说明:如果变量a大于变量b则执行问号后面的,否则就执行:冒号后面的
echo $c;
?>
Copy after login

The expression can be a function, array, etc.

In fact, the ternary operator can be extended and used. When the set condition is true or not, the execution statement can be more than one sentence. Try the following format:

(expr1) ? (expr2).(expr3) : (expr4).(expr5);
Copy after login

us It is very obvious to see that multiple execution statements can be connected using the string operator ("."). Each execution statement is surrounded by small angle brackets to indicate that it is an independent and complete execution. statement. After this expansion, its function is closer to the "if...else" process statement.
At the same time, the ternary operator can also be used nested. For example, when a is greater than b: if a is less than c, then x=c-a otherwise x=a-c; otherwise when a is less than b: if b is less than c, then x=c-b otherwise x=b-c:

$a>$b ? $x=($a<$c ? $c-$a : $a-$c) : $x=($b<$c ? $c-$b : $b-$c);
Copy after login

The readability of the nested ternary operator is not very good, and there may be problems with maintaining the code in the future, so in this case we should just use if else if to implement it.

The above is the detailed content of Detailed explanation of php ternary operator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template