The Ternary operator in PHP

Status
Not open for further replies.

Baljeet

Member
Jan 31, 2011
76
0
The Ternary comparison operator is an alternative to the if-else statement, it's shorter and could be used to easily do a significant difference depending on a condition without the need of a if statement. The Ternary operator is made for two different actions, one if the condition is true, the other one if it's false but with nested Ternary operators we can use it like an if-elseif.else statement(more to that later). The syntax of a Ternary operator looks like this:


PHP:
(condition) ? TRUE : FALSE

The Ternary operator will return either the first value(if the condition were true) or the second value (if the condition were false), so here comes a simple example on how we can use it:

PHP:
$siteFeedback = ($Site == "codecall") ? "Awesome" : "Unknown";

So what the example does is checking if $Site is equals to codecall, if it is "Awesome" will be stored in $siteFeedback but if it's not "Unknown" will be stored.

The above example would look like this with an if-else statement:

PHP:
if ($Site == "codecall") {
    $siteFeedback = "Awesome";
}else{
    $siteFeedback = "Unknown";
}



Since the Ternary operator returns a value we can use it for everything, not only storing different values in variables.

PHP:
echo "The current pupil " . (($pupils[$i] >= 15) ? "did" : "didn't") . " pass the test";

In the above example we're testing inside the echoing of a string if it should be "did" or "didn't" depending on how much points the pupil had. In this case we had to put the Ternary operator inside parentheses to make it work. In the example you saw how simple we could alter a string with a Ternary operator inside it. With an if-else statement we would have to first store "did" or "didn't" in a variable and then put it there instead. Or we could have wrote the same string twice with only the difference between "did" and "didn't" but that wouldn't have been so good if we wanted to alter the base string, then we would have to do it twice.





Nested Ternary operators

we can also nest them since they returns a value and each Ternary operator choose between two values so then we can only replace one (or both) value by another Ternary operator , like so:

PHP:
echo ($X > $Y) ? "X is greater then Y" : (($X < $Y) ? "Y is greater then X " : "X and Y has the same value.");

But this could be pretty hard to read so if you use nested Ternary operators you should find a good way to write it, an example could be writing it like this:

PHP:
echo ($X > $Y)  ?   "X is greater then Y" 
   : (($X < $Y) ?   "Y is greater then X" 
   :                "X and Y has the same value")
   ;



That was the end of the tutorial, I hope you liked it :)

All Credits goes to one who really made this...
 
Status
Not open for further replies.

Users who are viewing this thread

Top