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
- 17 Oct. 2010 04:53pm #1
PHP Ternary operator
Last edited by HTML; 22 Oct. 2010 at 12:41am.
- 18 Oct. 2010 12:33am #2
- 18 Oct. 2010 01:25am #3
- 25 Oct. 2010 07:33am #4
If anyone says ternary operators aren't useful they aren't schooled properly in the art of programming. Either way, short of minifying your code, it's good practice not to get too complicated with it. Your second example is getting difficult to understand, and anything beyond that even moreso.
The syntax is fairly universal in other languages.
- 25 Oct. 2010 01:48pm #5
- 25 Oct. 2010 04:46pm #6