Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

PHP Shorthand If / Else Examples

10 Responses »

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

Discussion

  1. ovidiu c.
    December 18, 2007 @ 10:00 am

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

    The == operator returns a boolean.

  2. December 18, 2007 @ 10:27 am

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

  3. December 19, 2007 @ 2:45 am

    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. August 25, 2009 @ 4:02 pm

    Nice – I always forget shorthand if statements

  5. max
    December 4, 2009 @ 4:01 am

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

  6. toad78
    March 10, 2010 @ 2:11 am

    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. March 18, 2010 @ 8:48 am

    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.

  8. May 19, 2010 @ 5:12 pm

    Can I do same thing with “elseif” statement?

  9. guy
    May 27, 2010 @ 9:17 am

    @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
    July 26, 2010 @ 7:33 pm

    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.

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!