PHP: Ternary Operator

Filed Under (General) by Wenbert on 07-05-2008

Tagged Under : ,

This is one my favorites. Sometimes I use this when I come around “short” conditions in variable assignments.

Instead of writing something like this:

if (isset($myvar)) {
    $temp = $myvar;
} else {
    $temp = ""; //i need to set this so that when I echo this, it won’t show a warning
}
 

I just use the ternary operator to make things easier to read by doing something like this:

$temp = isset($myvar)?$myvar:"";
 

Now how does it work? Basically, the syntax of the ternary operator is:
(condition)?“execute when true”:“execute when false”
On first glance it is confusing to use, but trust me, once you get the hang of it, you won’t be able to live without it.

Comments:

2 Responses to “PHP: Ternary Operator”


  1. I agree…the Ternary operator is the best.. It saves a lot of lines of coding. Though i do agree that it takes some time to get use to writing if/else like this.


  2. It took me a couple of days to get used to it. What I did is that I got a small piece of paper and wrote the syntax and posted it on the side of my monitor. Some sort of cheatsheet…

Leave a Reply

Subscribe to Rss Feed : Rss