Treehouse

PHP Shorthand If/Else Using Ternary Operators (?:)

By on  

An essential part of programming is evaluating conditions using if/else and switch/case statements. If / Else statements are easy to code and global to all languages. If / Else statements are great but they can be too long.

I preach a lot about using shorthand CSS and using MooTools to make JavaScript relatively shorthand, so I look towards PHP to do the same. If/Else statements aren't optimal (or necessary) in all situations. Enter ternary operators.

Ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures.

What Does Ternary Logic Look Like?

/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

What Are The Advantages of Ternary Logic?

There are some valuable advantages to using this type of logic:

  • Makes coding simple if/else logic quicker
  • You can do your if/else logic inline with output instead of breaking your output building for if/else statements
  • Makes code shorter
  • Makes maintaining code quicker, easier
  • Job security?

Tips for Using Ternary Operators

Here are a few tips for when using "?:" logic:

  • Don't go more levels deep than what you feel comfortable with maintaining.
  • If you work in a team setting, make sure the other programmers understand the code.
  • PHP.net recommends avoiding stacking ternary operators. "Is [sic] is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious."
  • If you aren't experienced with using ternary operators, write your code using if/else first, then translate the code into ?'s and :'s.
  • Use enough parenthesis to keep your code organized, but not so many that you create "code soup."

More Sample Usage

Here are a couple more uses of ternary operators, ranging from simple to advanced:

 /* another basic usage */
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
 /* shorthand usage */
$message = 'Hello '.($user->get('first_name') ?: 'Guest');
 /* echo, inline */
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody'); //harsh!
 /* a bit tougher */
$score = 10;
$age = 20;
echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? 'behind' : 'above average') : ($score < 50 ? 'behind' : 'above average')); // returns 'You are behind'
 /* "thankfully-you-don't-need-to-maintain-this" level */
 $days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31)); //returns days in the given month

To learn more about ternary operators and usage, visit PHP.net Comparison Operators.

ydkjs-4.png

Recent Features

  • CSS&nbsp;Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet...

  • CSS vs. JS Animation: Which is&nbsp;Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native...

  • 9 More Mind-Blowing WebGL&nbsp;Demos

    With Firefox OS, asm.js, and the push for browser performance improvements, canvas and WebGL technologies are opening a world of possibilities.  I featured 9 Mind-Blowing Canvas Demos and then took it up a level with 9 Mind-Blowing WebGL...

Incredible Demos

  • 5 More HTML5 APIs You Didnât Know&nbsp;Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us...

  • Create Custom Events in MooTools&nbsp;1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript /* click -...

  • MooTools TextOverlap&nbsp;Plugin

    Developers everywhere seem to be looking for different ways to make use of JavaScript libraries. Some creations are extremely practical, others aren't. This one may be more on the "aren't" side but used correctly, my TextOverlap plugin...

Discussion

  1. Nice job clarifying this! I keep forgetting the exact syntax for some reason…

  2. Your second echo example in the more examples is missing the first ‘e’ in the code.

  3. Mikkel Lund

    Nice article. I use this all the time. Often if/else statements get way too complicated. I love to shorten code and the (?:) operator helps a lot. It’s even a lot better when you can shorten it more than a (?:) can do: Yesterday I saw this excample in a high-end PHP OOP book:

    if ($condition){
    return true;
    }
    else {
    return false
    }

    It’s a lot easier to just use:

    return condition;

  4. I’ve been looking for a good explanation of this, thank you.

    Now I’m off to scour my code for opportunities to practice.

  5. ohh wow man, i really needed this
    thanks for sharing that with such nice explanation

    thanks again

  6. @Richard:

    If you have some experience with Javascript I would say that it is similar to:

    var test = result || error; //Javascript
    $test = $result ?: $error; //PHP

    In which it would return “result” value if it is not empty [1]. Otherwise it will return “error” value.

    I hope I was clear.

    [1] : For empty values see: http://www.php.net/manual/en/function.empty.php

  7. Oussama

  8. Danny

    /* echo, inline */
    echo ‘Based on your score, you are a ‘,($score > 10 ? ‘genius’ : ‘nobody’); //harsh!

    I think you may a typo with the ‘,’ instead of a ‘.’

  9. These are nice shorthands, but be warned, it will make your code unreadable and less understandable.

  10. GTershel

    Question

    What is wrong with this code, I keep receiving an error.
    Creating a sticky form and I am using a simple if (submit) then ($_POST['value'])

    
    Please enter your short description of the category (blurb):
            <textarea id="catblurb" name="catBlurb"  value="
            ">
            Please enter a small description about this category.
            
    

    I only need the if part of the if/else.

    Thanks for any help

    • strykr

      For people that might see this when searching..

      $_POST['value'] should be $_POST['catBlurb']

  11. David

    Hey Dave!
    I don’t use ternary very often, but is really nice in spots where things need to be tidy.

    I have a bit of a word of advice here on the use of ternary and collaboration. Dave addresses that in his points above, “Tips for Using Ternary Operators”.

    As a rule I use ternary only if the If/Else is a ‘single line of code’ <— Yes this is variable depending on screen size. Just don't go overboard when working collaboratively or if there is a chance some-one else will inherit the code.

  12. Eight

    Great article.
    In the first example, I think it’s the same thing as doing :
    $var_is_greater_than_two = ($var > 2);
    Right ?

  13. Excellent… would be. But parts of the page does not display under Opera/NetBSD. Please fix it. TIA

  14. kirk bushell

    Good article, I’m glad some poeple cover this. One thing should be mentioned though – this should definitely not be used heavily. Embedded ternary operators, and nested ternary operators are a developer’s worst nightmare – it creates unnecessarily unreadable code that is difficult to maintain. Sometimes more code is better! :)

  15. Imam Tauhid

    i’am looking for this thing , thx for your explanation bro.

  16. [...] am recommending that instead of using isset() everywhere, we leverage the @ (error suppression) and ?: (shorthand ternary) operators to test for [...]

  17. Thank you for this explanation. I have a background in Java so coming to PHP I see many similar coding between the two. This is one of them. But I wanted to make sure its the same in both and found you via Google when searching.

  18. [...] use of ternary operators in your code frees up your line space and makes your code less cluttered and thus makes it ideal [...]

  19. [...] data. Then we define an empty array that will hold all the data we want to save. Next we use a one line conditional conditional statement that says $term_meta['tax_image'] is equal to [...]

  20. Sky

    “Makes maintaining code quicker, easier” – I’d say that it’s quote contrary. It makes it more difficult and obscure, not easier (these statements are by far easier to accidentally skip or misunderstand while analysing the code than regular ifs).

  21. Thanks, David! You’re doing great job revealing PHP mysteries.

  22. kil

    so, can i shorten this if else using ternary?

    if(1==$c){
            $a=10;
            $b=12;
    }
    elseif(2==$c){
            $a = 9;
            $b = 27;
    }
    elseif(3==$c){
            $a=11;
            $b=8;
    }else{
            $a = 0;
            $b = 0;
    }
    
  23. [...] Here you can see the usage of ternary if operator: [...]

  24. ahmad

    wish we had a syntax to test something and assign it to l_value if the test was successfull
    like
    y = x > 4 ?; means y = x if x > 4

    or

    y = x > 4 ? : z; means y= x if x > 4 else y = z would be a shorthand for
    y= x > 4 ? x : z

    Note usually when we test a condition on a variable we want to assign the same value as above

    then we could have

    y = x > 4 ? w : z; means y = w if x > 4 else y = z

  25. Thanks.. This was just what I was looking for!

  26. MT

    Thanks… That is what i am looking for, sample usage attracts me!

  27. Jols (Bardz)

    Thanks bro, now I understand :)

  28. [...] use of ternary operators in your code frees up your line space and makes your code less cluttered and thus makes it ideal [...]

  29. [...] More info can be found at davidwalsh [...]

  30. [...] using a more succinct method of checking values using ternary operators, you could use a set of if {} else {} conditions over several [...]

  31. [...] building html which, IMO, is REALLY AWESOME, It keeps the code clean and readable. Also, learning Ternary shorthands for if/else statements saved me a few lines of [...]

  32. [...] controlliamo il valore di votes, se è nullo gli assegnamo “0″, non è ancora stato votato, altrimenti lo lasciamo invariato. Per chi non conoscesse questa sintassi, abbiamo usato un operatore ternario che ci permette di scrivere una condizione di controllo in forma compatta, un po di linee guida per l’utilizzo di un operatore ternario. [...]

  33. Andreas Burg

    Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
    http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

    You should show an example e.g.

    echo $username ?: ‘unknown’;
    // same as
    echo $username ? $username : ‘unknown’;

    • John

      Thanks for clarifying this only works from PHP 5.3+, I was getting nuts trying to figure it out why it wasn’t working.

  34. Unlike (literally!) every other language with a similar operator, ?: is left associative. So this:

      $arg = 'T';
      $vehicle = ( ( $arg == 'B' ) ? 'bus' :
                   ( $arg == 'A' ) ? 'airplane' :
                   ( $arg == 'T' ) ? 'train' :
                   ( $arg == 'C' ) ? 'car' :
                   ( $arg == 'H' ) ? 'horse' :
                   'feet' );
      echo $vehicle;
    

    Will output: horse

  35. […] the isset()  statement – a PHP conditional statement is used to to test whether the script has values for current page.   the isset is used in conjunction with a shortcut version of the if statement using tertiary operators. […]

  36. Wow! I did not know that you don’t have to put a value after the question mark i.e. that you can do this:

    var $myvar = 'Hello ' . $test ?: ' World';

    Can I also do this:

    var $myvar = 'Hello ' . $test ? ' World' :;

    Or will that throw an error?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Use Code Editor