Syntax: Condition? Result 1: Results 2
Description: The position of the front of the question mark is the condition of judgment, if the condition is satisfied with the result 1, the result is not satisfied 2.
The code is as follows |
|
? Php $id = Isset ($_get[' id ')? $_get[' id ': false; ?> |
A piece of code replaces a lot of code. First, it uses the Isset () function to check if the $_get[' ID ' exists. If $_get[' id ' does exist, it returns its value. However, if it does not exist, the condition is false, and false is returned. The value $id depends on whether the $_get[' id ' exists. So, basically, if the $_get[' id ' exists, $id =$_get[' id '], and vice versa $id=false.
Cases
Validate user input values with the "?:" Conditional statement:
The code is as follows |
|
<?php $filename = Isset ($argv [1])? $ARGV [1]: "Php://stdin"; $fp = @fopen ($filename, ' r ') or Die ("Can ' t Open $filename for reading"); while (! @feof ($fp)) { $line = @fgets ($fp, 1024); Print $line; } @fclose ($FP); ?> |
The previous code using the ternary operator is equivalent to the following code:
The code is as follows |
|
<?php if (Isset ($argv [1])) { $filename = $argv [1]; } else { $filename = "Php://stdin"; } ?> |
It can be seen that, assuming the normal if-else structure to write the above code, the amount of code will be more than the above, but the second form is easier to understand, and does not require more input. So when choosing ternary operators, make sure you weigh the pros and cons.
Advantages of ternary operators
The ternary operator (?:) in PHP greatly reduces the time that programmers write these statements. Its syntax is as follows:
Condition? Do_if_true:do_if_false;
The ternary operator is not an essential structure, but it is a way to beautify the code. Again, it can replace bad If...else code blocks and improve the readability of your code.
Similarly, a user can use the PHP or operator service to assign a variable default value:
The code is as follows |
|
<?php $filename = $argv [1] or $filename = "Php://stdin"; ?> |