Home >Backend Development >PHP Tutorial >Detailed explanation of php ternary operator

Detailed explanation of php ternary operator

怪我咯
怪我咯Original
2017-06-20 13:57:204923browse

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

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;
?>

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

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

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!

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