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();Discussion
Be Heard!
Share your thoughts with fellow developers of all skill levels! I want to hear from you!
$is_admin = ($user['permissions'] == ‘admin’ ? true : false);
is equivalent to:
$is_admin = $user['permissions'] == ‘admin’;
The == operator returns a boolean.
Good point Ovidiu. I wanted a really basic example using both the “?” and “:”. What you have is absolutely correct (and shorter)!
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..
Nice – I always forget shorthand if statements
little bug: when u view the code, the page scrolls so to upper semi-transparent block scrolls over your code.
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?
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.
Can I do same thing with “elseif” statement?
@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.
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.