Home >Backend Development >PHP Tutorial >PHP ternary operator combination and its use

PHP ternary operator combination and its use

伊谢尔伦
伊谢尔伦Original
2017-06-21 15:15:491897browse

The function of the ternary operation symbol is consistent with the "if...else" process statement. It is written in one line, and the code is very concise and the execution efficiency is higher.

Appropriate use of the ternary operator in PHP programs can make the script more concise and efficient.

The code format is as follows: (expr1) ? (expr2) : (expr3);

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

To achieve the same function, if you use conditional process statements, you need to write multiple lines of code:

if(expr1) { 
expr2;
} else {
expr3;
}

It can be seen that the goodness of the ternary operator mentioned above is not an exaggeration. However, in most cases we only use the ternary operator when the code is relatively simple, that is, when the execution statement is only a single sentence. For example:

$a>$b ? print "a大于b" : print "a小于b";

In fact, the ternary operator can be extended. 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);

We are very obvious As you can see, 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=($a8e352089f6fba2526e34e18ea549fd8a true.
I don’t know if this process is a pain in the butt, it is indeed difficult to understand...
Finally, go back to the above code again and change it into a right combine like C:

<?php 
$a=1;$b=2;$c=3;$d=4; 
echo $a<$b?&#39;xx&#39;:($a<$c?&#39;yy&#39;:($a<$d?&#39;zz&#39;:&#39;oo&#39;)); 
// 括号换下位置就行了, php里括号省不得 
?>

The above is the detailed content of PHP ternary operator combination and its use. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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