View Full Version : Tertiary (if/else)


pb&j
02-13-2003, 12:32 PM
Originally posted by Ökii
tertiary (short if/else) operator

( a = b ) ? [do if true] : [do if false] ;
echo (7 > 4) ? 'true' : 'false'; => true
echo (7 < 4) ? 'true' : 'false'; => false

the first clause after the ? is assigned if the parenthesised expression equates to true, else the second clause is.
only works for single method clauses tho.
Tertiary is cool. So are additional elseif represented by further question marks?

( a = b ) ? [do if true] ? [do if first false but this true] : [do if false];

Ökii
02-14-2003, 08:50 AM
php and javascript handle tertiary (some people prefer 'ternary') operators in different manners as far as I'm aware.

In both languages you could do

var = (a < 4) ? (a < 3) ? (a < 2) ? 'one' : 'two' : 'three' : 'default';

and I believe js would accept

var = (a == 4) ? 'four' : (a == 3) ? 'three' : 'default';
*untested*

they are only a short replacement for if/else or switch (hence tertiary = 3rd way of writing if/else) statements when the logic isn't heavy and the method is singular - ie you couldn't do

(a == 7) ? echo 'blat'; exit : echo 'fooey'; exit

getting longer ternary operators to work properly with == operands is very tricky - a switch case statement would probably be better.

pb&j
02-14-2003, 01:29 PM
Ah, cool. Thanks.