Today we are going to explain in PHP operator "
Ternary operators”。
Introduction to Ternary operators
The ternary operator is often used in programming, which is also called the "Trinocular operator", as his name requires three operands, and his role is to select one of the other two expressions based on an expression instead of selecting one in two statements or programs. Let's take a look at the syntax of the ternary operator.
Syntax for ternary operators
Ternary operator with (? :) said, the following wording
Conditions? Result 1: Result 2
When the condition is met, select result 1, otherwise it will be result 2, and we'll use an example to illustrate it later.
The role of ternary operators and PHP if...else ... Process statements, however, the ternary operator writes in one line, the code is small, and the execution is much more efficient.
Ternary operator Instances
This example uses the ternary operator to implement a simple selection function, if the condition is set to output "topic.alibabacloud.com", otherwise the output "false", the instance code is as follows:
<?phpheader ("Content-type:text/html;charset=utf-8"); Set the encoding $a=100; Description of a variable $b= ($a ==true?topic.alibabacloud.com:false); Echo $b;? >
Code Run Result:
Above we say the role of ternary operators and PHP if...else ... Process statements, then we use if....else ... The process statement is written over the example above, the code is as follows
<?phpheader ("Content-type:text/html;charset=utf-8"); Set the encoding $a=100; if ($a ==true) { echo "topic.alibabacloud.com";} Else{ echo "false";}? >
Code Run Result:
You can see that two examples run the same result.
PS: Although ternary operation and If...else ... Process statements, but in most cases we only use ternary operators when the code is simpler.
Above is the simple use of ternary operators