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();
is equivalent to:
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)!
You should also use
===
operator instead of
==
. It’s faster because does not try to convert types if they don’t match.
Thank you for showing it the way you did, it gave me the clue I was looking for to replace
with
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.
why would it not just return false?
Can I do same thing with “elseif” statement?
@Landish: the second part of the shorthnad (when the statement evaluates to false) can be used for elseif:
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.
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!
what about this ?
$module ? $modules[$module] = $path : $modules = array();
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… :)
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
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?
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!
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 !!!!!!
great article. its easy to go a little nuts with shorthand conditionals given this knowledge :)
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?
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;
Thought I would include this extreme shorthand example that I use all the time based off this:
Tall enough to ride?
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.
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";
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!
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
$perms = true;
$var = ($perms ?: 'Hello World');
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.
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.
this is insanely helpful. thanks.
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.
Thanks for this examples, helped me a lot!
Bogdan
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
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!
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';
Hi there.
Is it a real improvement to use shorthand If/else over the good ol’ if / then sentences?
Shorthand if else is not readable and is highly not recommended for complex type applications.
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!
We can mention this too:
if
$bar
istrue
, execute$bar
else execute$string
;THANK YOU ALL!!!