PHP Shorthand If / Else Examples

By  on  

In looking at my Google Analytics statistics, I see a lot of visitors searching for PHP shorthand if/else (ternary) information. I've gone through my code library and picked out some examples of ternary operator usage.

Basic True / False Declaration

$is_admin = ($user['permissions'] == 'admin') ? true : false;

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Conditional Items Message

echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';

Conditional Error Reporting Level

error_reporting($WEBSITE_IS_LIVE ? 0 : E_STRICT);

Conditional Basepath

echo '<base href="http'.($PAGE_IS_SECURE ? 's' : '').'://mydomain.com" />';

Nested PHP Shorthand

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

Leap Year Check

$is_leap_year = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));

Conditional PHP Redirect

header('Location: '.($valid_login ? '/members/index.php' : 'login.php?errors=1')); exit();

Recent Features

  • By
    I&#8217;m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    Chris Coyier&#8217;s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

Incredible Demos

  • By
    AJAX For Evil:  Spyjax with jQuery

    Last year I wrote a popular post titled AJAX For Evil: Spyjax when I described a technique called "Spyjax": Spyjax, as I know it, is taking information from the user's computer for your own use — specifically their browsing habits. By using CSS and JavaScript, I...

  • By
    Background Animations Using MooTools

    One of the sweet effects made easy by JavaScript frameworks like MooTools and jQuery is animation. I ran across this great jQuery tutorial that walks you through animating a background image of a page. Here's a quick MooTools code snippet that...

Discussion

  1. Ovidiu C.
    $is_admin = ($user['permissions'] == 'admin' ? true : false);

    is equivalent to:

    $is_admin = $user['permissions'] == 'admin';

    The == operator returns a boolean.

  2. Good point Ovidiu. I wanted a really basic example using both the “?” and “:”. What you have is absolutely correct (and shorter)!

    • Justinas

      You should also use === operator instead of ==. It’s faster because does not try to convert types if they don’t match.

    • Simon

      Thank you for showing it the way you did, it gave me the clue I was looking for to replace

      if(variable == 1 ) echo "Yes" ;
      else echo "No"; 

      with

      echo ($variable == 1 ) ? "Yes" : "No"
  3. hey,
    nice compilation…
    will add a bookmark to come to this when needed…

    anyone knows of a way to organize code snippets. which can then be used from Eclipse PDT (http://eclipse.org/pdt) or Zend Studio..
    am looking for something like that for some time..

  4. Nice – I always forget shorthand if statements

  5. Max

    little bug: when u view the code, the page scrolls so to upper semi-transparent block scrolls over your code.

  6. toad78

    How would I create a condition statement for the following situation:

    I have a table in a loop that displays results of runners organized by age ($row_getResults[‘heading’]) then organized by whether they ran the ‘1 Mile’ ($row_getResults[‘mile’]) or the ‘8K’.

    The table has ” headers of:
    Place
    Name
    City
    Bib No.
    Age
    Overall
    Time
    Pace

    within each ” cell in a row below the heading ($row_getResults[‘heading’]). The queried content displays correctly and is organized just fine. What I need help is to not have the ” repeat if the content falls under the same $row_getResults[‘heading’]. I only want one ” row per table of results.

    The following results are displayed with one table:
    Place Name City Bib No. Age Overall Time Pace
    1 Scott Mac Sunnyvale, CA 12 9 12 3:00.3 3:00/M
    Place Name City Bib No. Age Overall Time Pace
    2 Jerry Marc Los Angeles, CA 11 12 9 4:12.1 4:12/M

    Imagine how this looks with 100 records. EEK!

    The ” row is static.

    THE CODE:

    <?php if ($row_getResults['mile'] !=$mile) { echo "”.$row_getResults[‘mile’].””; $mile = $row_getResults[‘mile’]; } ?>
    <?php if ($row_getResults['heading'] !=$heading) { echo "”.$row_getResults[‘heading’].””; $heading = $row_getResults[‘heading’]; } ?>

    Almond Blossom Fun Run 2010 Results

    Place
    Name
    City
    Bib No.
    Age
    Overall
    Time
    Pace

    Would a conditional statement solve the problem?

  7. I use something like this a lot:

    $is_admin = (isset($[user[‘permissions’]) ? $[user[‘permissions’] : ”);

    Because if $[user[‘permissions’] is unset and I were to just say

    $is_admin=$[user[‘permissions’];

    It would throw an ‘Undefined Index’ Notice… Which isn’t a true error.. but still.

    • Jenn

      why would it not just return false?

  8. Can I do same thing with “elseif” statement?

  9. Guy

    @Landish: the second part of the shorthnad (when the statement evaluates to false) can be used for elseif:

    $somevalue == 'foo' ? 'is foo' : ($somevalue == 'bar' ? 'is bar' : 'is neither');
    

    I’d rather just use elseif() {} if you need it, though. Helps with readability IMO.

  10. Sid

    Your site is cool and all – but it is barely useable.

    Parts of the code examples are hidden behind the buttons – “Get raw code”, etc. And when you click on it to look at the full code – it scrolls up and is hidden under the semi-transparent bar you got on top.

  11. Thanks for that! This has come in handy for a CRUD from design I was working on.
    I’ve also referenced this from my blog.

    Cheers!

  12. mehmet

    what about this ?

    $module ? $modules[$module] = $path : $modules = array();

  13. neeraj singh

    Hi, David
    I like your blog very much. I like to do some R&D with Dojo, Moo tools, JQuery. Basically I am a PHP Developer. I am appreciating your efforts very much. Really it is very hard to maintain blog with some interesting tricky code. David trust me we check your blog every day to find something new and we never in loss. We salute you. I have a suggestion for you that what about if you make a forum for discussion some blasting issues in your blog. Kindly Continue… :)

  14. Great post – very helpful and yes, exactly what I was searching for. What I don’t get is why this is missed out of so many PHP books. It’s kinda an intermediate bit of knowledge, but so many books are either too basic or more advanced. I think the only place I have ever seen this is in my PHP cookbook, and as I can’t find that right now, you just saved me a headache :D thx

  15. mike

    Hi David,

    Need your help. Can you?

    I am relenting to the email source, forums and blogs out here. I am trying to kick myself in the rear and just create php code on my own and it is just not working so instead I have to reach out for help.

    I want to do a simple script where if a text value is not entered in an email form, When the email is sent to me, I want it to display,

    “NO DATA” in the field I designate for it… example in my form “Date of Service: NO DATA” but, if the customer entered something in the field it will display properly…. “Date of Service: 09/12/11”.

    Again let me express this is all for the post “send” on the back end, NOT for the customer to see, but for me to see it when emailed to me.

    This is my code:

    **what am I doing wrong? can you help?

  16. mike
    
    	$no_data = "NO DATA";
    	$date = $_POST['date'];
    
    		if($date==""){
    			$_POST["$no_data"]
    			
    }
    		else $_POST["$date"]
    		return false;
    
    
    $message ="
    
    This is the: $date
    
    ";
    
  17. Every time I get a little bit confused with conditional shorthand I seem to search and find this article I should bookmark it now as I always find it most helpful! Thanks David!

  18. TitoChhabra

    Hello Everyone,
    ‘If… Else’ statement is used to perform different action for different decision. Conditional (relational operator) statements are used to perform different action on basis of different decision. So we can say that ‘If…Else’ statement generally used with conditional statement………….. for more details please check out this link….
    http://mindstick.com/Articles/a3394e30-37b0-45e9-9e5d-8beffd1ba7dc/?If%E2%80%A6Else%20Statement%20in%20PHP

    thanks !!!!!!

  19. great article. its easy to go a little nuts with shorthand conditionals given this knowledge :)

  20. Hi, I have this code:

    $r = myfunction($param) ;
    return $r ? $r : anotherfunction();

    I want to short it, but I can’t call myfunction() twice. Is any chance to short it?

  21. Nice work thanks for sharing i’ve re-wrote a script of mine and it’s lot smaller now.
    Many thanks and great site glad you got it back,
    Ian

    $title = (!empty($tags['title']) ? $SpGr.$tags['title'] : $SpRe.'No title found').$SpCl;

  22. Thought I would include this extreme shorthand example that I use all the time based off this:


    Tall enough to ride?

  23. Hmm apparently you can’t show php tags in the code tags. Anyway.. if you look at the source you can see it commented out or maybe David can fix it.

  24. I’ve been referring back to this post a lot, thanks! In working with a lot of javascript lately, I realized the shorthand for conditional logic is pretty much identical. So there is another statement you could add to this list- An ‘if’ statement with no else can be written like this without the curly braces:

    if ($myVar) echo "$myVar is true";

  25. Bryan De Asis

    This is another simple if condition.

    $var = "nothing";
    (true) && $var = "true";
    echo $var;

    Meaning using && you are expecting the return of the condition to be true; If the condition is false it will not substitute the new value.


    $var = "nothing";
    (false) || $var = "false";
    echo $var;

    Using || you are expecting the return of the condition to be false; If the condition is true it will not substitute the new value.

    Hope this helps on optimizing conditions. Just play with it and you will discover more. Cheers!

  26. david

    Your content shows only after everything loaded. that’s not good. I ad top leave and come back again twice before I see the codes

  27. Martin


    $perms = true;
    $var = ($perms ?: 'Hello World');

  28. As someone who is only getting to know PHP, seeing raw shorthand doesn’t help if I don’t have the longhand version compare it with.

    Still, a useful resource; bookmarked so I can come back when the fog of learning lifts.

  29. Brandon

    Come on guys. this isn’t shorthand. This what’s called a conditional operator. This is shorthand:

    isset($_GET[‘test’]) && print $_GET[‘test’];

    The above line will only execute the print statement IF the variable is set. That’s what shorthand is. The conditional operator is great too, but it’s not shorthand. it’s just an operator.

  30. leif

    this is insanely helpful. thanks.

  31. Menno

    This is crap, you should ad normal if notation translations. I don’t get this. Please show us what normal if notation of these examples will look like.

  32. Thanks for this examples, helped me a lot!

    Bogdan

  33. Franko

    Thank you fot the effort to put this on the web. It’s just what I was looking for.

    May the force be with you :)

    Franko

  34. Joseph Ryan Wagner

    Thank you so much for putting this up. I was looking for precisely this and it was a huge help. A heartfelt hat tip to you good sir!

  35. 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';

  36. Scyfox

    Hi there.

    Is it a real improvement to use shorthand If/else over the good ol’ if / then sentences?

  37. Shorthand if else is not readable and is highly not recommended for complex type applications.

  38. Daniel

    I’ve referred to this page a couple dozen times already to quickly get the shorthand syntax. Just wanted to say thanks for posting this!

  39. Lyubomir Angelov

    We can mention this too:

    $string = 'string';
    $bar = true;
    $bar || $string;
    

    if $bar is true, execute $bar else execute $string;

  40. David

    THANK YOU ALL!!!

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