Home>Article>Backend Development> How to write ternary expression in php
In PHP, ternary expressions can implement simple conditional judgment functions. The writing method is "expression 1? expression 2: expression 3"; if the condition "expression 1" is established, the statement is executed "Expression 2", otherwise execute "Expression 3".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Ternary operation in php
Ternary operation can implement a simple conditional judgment function, that is, based on the result of the first expression, select one of the other two expressions and execute
Ternary operation expression The way of writing:
表达式1?表达式2:表达式3
means: if the condition "Expression 1" is true, execute the statement "Expression 2", otherwise execute the "Expression 3"
The sample code is as follows:
The running results are as follows:
$a 是偶数!
In addition,Expression 2
andExpression 3
can also use single quotes ('')
or double quotes (""
) to omit any one of them to avoid unnecessary code, as shown below:
' : ""; $b % 2 == 0 ? '' : print '$b 是奇数!'; ?>
The running result is as follows:
$a 是偶数! $b 是奇数!
Note: When using ternary arithmetic, if you need to print a string, it is recommended to use the print statement instead of the echo statement.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to write ternary expression in php. For more information, please follow other related articles on the PHP Chinese website!