Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Last active October 27, 2020 11:35
Show Gist options
  • Save fmtarif/629b97b430375e11e15a to your computer and use it in GitHub Desktop.
Save fmtarif/629b97b430375e11e15a to your computer and use it in GitHub Desktop.
#php non obvious behavior of nested ternary
<?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