A preserved archive of the Logical Gamers community forums, 2009-2025. The original threads and posts, served read-only. Registration, posting and private messages are gone for good.

PHP Ternary operator

1.4k views · started by HTML ·
#1
PHP Ternary operator
Here's a small example of how to use the ternary operator in php, instead of using if and else.

If else statement
if(cool == false){
echo"cool is equal to false";

} else{
echo"cool is not equal to false";

}

Here's the same thing, but using the ternary operator.

$cool == false ? 'Cool is false' : 'Cool isn\'t false'



lets try nesting if's but with the ternary operator.
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";
}

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
#2
You can just use switch statements.
#3
Chad wrote:
You can just use switch statements.


Yeah, but this is an example of an if else simple alternative, I use it when my if else's have one or two conditions.

but yeah, for the example above a switch would be easier of course..
#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.
#5
Very useful for quick returns. Can get rid of several lines of code for such simplicity.
#6
Arti wrote:
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.


Yes, the second example is a little extereme and of course I would just suggest using a switch, but I just wanted to let people know it was possible to nest if's.