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.

Subscribe to Rss Feed : Rss