Here's a small example of how to use the ternary operator in php, instead of using if and else.
Here's the same thing, but using the ternary operator.Code:If else statement if(cool == false){ echo"cool is equal to false"; } else{ echo"cool is not equal to false"; }
Code:$cool == false ? 'Cool is false' : 'Cool isn\'t false'
lets try nesting if's but with the ternary operator.
Code:If(number == 1){ echo "Num = 1"; If(number == 2){ echo "Num = 2"; } If(number == 5){ echo "Num = 5"; } } else{ echo "The number is not 1 - 5"; }Code:echo ($number == 1 ? 'Num=1' : ($num == 2 ? 'Num=2' : ($num == 5 ? 'Num=5' : 'Number is is not 1 - 5')));
remember: (condition ? result : alternative_result);
Go here for more information:
PHP: Comparison Operators - Manual
Results 1 to 6 of 6
Thread: PHP Ternary operator
Threaded View
- 17 Oct. 2010 04:53pm #1
PHP Ternary operator
Last edited by HTML; 22 Oct. 2010 at 12:41am.