Home > Article > Backend Development > PHP Operator (8) 'Ternary Operator' Example Explanation
Today I will explain to you the "ternary operator" among PHP operators.
Introduction to the ternary operator
The ternary operator is often used in programming. It is also called the "ternary operator", just like its name. , it requires three operands, and its function is to select one of two expressions based on one expression, rather than selecting one between two statements or programs. Let’s take a look at the syntax of the ternary operator.
The syntax of the ternary operator
The ternary operator is represented by (?:) and is written as follows
条件?结果1:结果2
When the condition is met, select Result 1, otherwise it is result 2. We will use examples to illustrate it later.
The ternary operator has the same function as the if...else...process statement in PHP. However, the ternary operator is written in one line, with less code and high execution efficiency. a little.
Ternary Operator Example
This example uses the ternary operator to implement a simple selection function. If the condition is true, "PHP Chinese Network" will be output, otherwise it will be output "false", the example code is as follows:
<?php header("content-type:text/html;charset=utf-8"); //设置编码 $a=100; //说明一个变量 $b=($a==true?PHP中文网:false); echo $b; ?>
Code running result:
Above we talked about the role of the ternary operator and the if in PHP. ..else... process statements are the same, then we use if...else... process statements to write the above example again. The code is as follows
<?php header("content-type:text/html;charset=utf-8"); //设置编码 $a=100; if($a==true){ echo "PHP中文网"; }else{ echo "false"; } ?>
Code running results:
You can see that the results of the two examples are the same.
PS: Although the ternary operator is the same as the if...else...process statement, in most cases we only use the ternary operator when the code is relatively simple.
The above is a simple application of the ternary operator
Recommended related articles:
1.PHP Operator (1) "Arithmetic Operator" Example explanation
2.PHP operator (2) Detailed explanation of "String operator" example
3.PHP operator (3) "Assignment operator" example explanation
4.PHP operator (4) "Bit operator" example explanation
5.PHP operation Operator (5) "Logical operator" example explanation
6.PHP operator (6) "Comparison operator" example explanation
7.PHP Operator (7) "Error Control Operator" Example Example
The above is the detailed content of PHP Operator (8) 'Ternary Operator' Example Explanation. For more information, please follow other related articles on the PHP Chinese website!