Ternary operator, is a fixed format in software programming, i.e. (? :) (note: The content in parentheses is the correct format).
Syntax: Condition? Result 1: Result 2
Description: The position in front of the question mark is judged by the condition, if the condition is met when the result is 1, the result 2 is not satisfied.
The code is as follows |
Copy Code |
$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 ' is present. If the $_get[' id ' does exist, it will return its value. However, if it does not exist, the condition is false and the return is false. The value of the $id depends on whether the $_get[' id '] exists. So, basically, if $_get[' id ' exists, $id =$_get[' id '], and vice versa $id=false.
Cases
Verify user input values with the "?:" Conditional statement:
The code is as follows |
Copy Code |
$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 preceding code with the ternary operator is equivalent to the following code:
The code is as follows |
Copy Code |
if (Isset ($argv [1])) { $filename = $argv [1]; } else { $filename = "Php://stdin"; } ?> |
As you can see, assuming that the above code is written in a normal if-else structure, the code will be much larger than the above, but the second form is easier to understand and does not require more input. So when choosing the ternary operator, be sure to 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;
Ternary operators are not an essential structure, but they are a way to beautify the code. Again, it can replace bad if...else blocks of code, and can improve the readability of the code.
Similarly, users can assign default values to variables using PHP's OR operation clothing:
The code is as follows |
Copy Code |
$filename = $argv [1] or $filename = "Php://stdin"; ?> |
http://www.bkjia.com/PHPjc/628758.html www.bkjia.com true http://www.bkjia.com/PHPjc/628758.html techarticle ternary operator, is a fixed format in software programming, i.e. (? :) (note: The content in parentheses is the correct format). Syntax: Condition? Result 1: Result 2 Description: Ask ...