Last active
October 27, 2020 11:35
-
-
Save fmtarif/629b97b430375e11e15a to your computer and use it in GitHub Desktop.
#php non obvious behavior of nested ternary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $arg = 'T'; | |
| $vehicle = ( $arg == 'B' ) ? 'bus' : | |
| ( $arg == 'A' ) ? 'airplane' : | |
| ( $arg == 'T' ) ? 'train' : | |
| ( $arg == 'C' ) ? 'car' : | |
| ( $arg == 'H' ) ? 'horse' : | |
| 'feet'; | |
| echo $vehicle; | |
| //will echo horse not train | |
| $arg = 'T'; | |
| $vehicle = (( ( $arg == 'B' ) ? 'bus' : | |
| (( $arg == 'A' ) ? 'airplane' : | |
| (( $arg == 'T' ) ? 'train' : | |
| (( $arg == 'C' ) ? 'car' : | |
| (( $arg == 'H' ) ? 'horse' : | |
| 'feet' )))))); | |
| echo $vehicle; | |
| //will echo train | |
| //http://17thdegree.com/archives/2008/01/09/php-and-nesting-ternary-operators/ | |
| //http://www.php.net/manual/en/language.operators.comparison.php#example-138 | |
| /* explanation | |
| $test = 'one'; | |
| echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three'; | |
| What PHP will do is evaluate this the first ternary section and return a value, | |
| in this case it is the string ‘one’. | |
| The boolean value of the string ‘one’ is true. So, for the second ternary operation, ‘two’ gets selected. | |
| The way a nested ternary operator is evaluated in PHP is left to right. (Probably no other languages acts like this.) | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment