A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

PHP: Ternary Operator

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.

This entry was posted in General and tagged , . Bookmark the permalink.

2 Responses to PHP: Ternary Operator

  1. Shaun says:

    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. Wenbert says:

    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

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>