PHP Shorthand If / Else Examples

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();

Comments

  1. Ovidiu C.

    $is_admin = ($user['permissions'] == ‘admin’ ? true : false);
    is equivalent to:
    $is_admin = $user['permissions'] == ‘admin’;

    The == operator returns a boolean.

  2. david

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

  3. Bijay Rungta

    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. Trendy Wordpress Themes

    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. Brad

    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. Landish

    Can I do same thing with “elseif” statement?

  9. Guy

    @Landish: the second part of the shorthad (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. My name is Osama

    Thank you for posting this. Really needed it.

  12. Trevor

    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!

  13. mehmet

    what about this ?

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

  14. 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… :)

  15. Chris

    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

  16. 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?

  17. mike

    $no_data = "NO DATA";
    $date = $_POST['date'];

    if($date==""){
    $_POST["$no_data"]

    }
    else $_POST["$date"]
    return false;

    $message ="

    This is the: $date

    ";

  18. Blair Nichols

    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!

  19. 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 !!!!!!

  20. kevin

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

  21. paul

    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?

  22. Ian.J.Gough

    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;

  23. Jesse

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


    Tall enough to ride?

  24. Jesse

    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.


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: