- PHP Shorthand If/Else Using Ternary Operators (?:)
- What Does Ternary Logic Look Like?
- What Are The Advantages of Ternary Logic?
- Tips for Using Ternary Operators
- More Sample Usage
- Recent Features
- 9 Mind-Blowing WebGL Demos
- How to Create a Twitter Card
- Incredible Demos
- CSS Columns
- MooTools Documentation Search Favelet
- Discussion
- Php ternary operator short
PHP Shorthand If/Else Using Ternary Operators (?:)
An essential part of programming is evaluating conditions using if/else and switch/case statements. If / Else statements are easy to code and global to all languages. If / Else statements are great but they can be too long.
I preach a lot about using shorthand CSS and using MooTools to make JavaScript relatively shorthand, so I look towards PHP to do the same. If/Else statements aren’t optimal (or necessary) in all situations. Enter ternary operators.
Ternary operator logic is the process of using «(condition) ? (true return value) : (false return value)» statements to shorten your if/else structures.
What Does Ternary Logic Look Like?
/* most basic usage */ $var = 5; $var_is_greater_than_two = ($var > 2 ? true : false); // returns true
What Are The Advantages of Ternary Logic?
There are some valuable advantages to using this type of logic:
- Makes coding simple if/else logic quicker
- You can do your if/else logic inline with output instead of breaking your output building for if/else statements
- Makes code shorter
- Makes maintaining code quicker, easier
- Job security?
Tips for Using Ternary Operators
Here are a few tips for when using «?:» logic:
- Don’t go more levels deep than what you feel comfortable with maintaining.
- If you work in a team setting, make sure the other programmers understand the code.
- PHP.net recommends avoiding stacking ternary operators. «Is [sic] is recommended that you avoid «stacking» ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious.»
- If you aren’t experienced with using ternary operators, write your code using if/else first, then translate the code into ?’s and :’s.
- Use enough parenthesis to keep your code organized, but not so many that you create «code soup.»
More Sample Usage
Here are a couple more uses of ternary operators, ranging from simple to advanced:
/* another basic usage */ $message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
/* shorthand usage */ $message = 'Hello '.($user->get('first_name') ?: 'Guest');
/* echo, inline */ echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody'); //harsh!
/* a bit tougher */ $score = 10; $age = 20; echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? 'behind' : 'above average') : ($score < 50 ? 'behind' : 'above average')); // returns 'You are behind'
/* "thankfully-you-don't-need-to-maintain-this" level */ $days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31)); //returns days in the given month
To learn more about ternary operators and usage, visit PHP.net Comparison Operators.
Recent Features
9 Mind-Blowing WebGL Demos
How to Create a Twitter Card
Incredible Demos
CSS Columns
MooTools Documentation Search Favelet
Discussion
Nice article. I use this all the time. Often if/else statements get way too complicated. I love to shorten code and the (?:) operator helps a lot. It’s even a lot better when you can shorten it more than a (?:) can do: Yesterday I saw this excample in a high-end PHP OOP book: if ($condition) <
return true;
>
else <
return false
> It’s a lot easier to just use: return condition;
Mind you, the if-statement you supplied checks if $condition is NOT false, everything else will pass, which might not always be ideal.
I’ve been looking for a good explanation of this, thank you. Now I’m off to scour my code for opportunities to practice.
@Richard: If you have some experience with Javascript I would say that it is similar to: var test = result || error; //Javascript
$test = $result ?: $error; //PHP In which it would return “result” value if it is not empty [1]. Otherwise it will return “error” value. I hope I was clear. [1] : For empty values see: http://www.php.net/manual/en/function.empty.php
/* echo, inline */
echo ‘Based on your score, you are a ‘,($score > 10 ? ‘genius’ : ‘nobody’); //harsh! I think you may a typo with the ‘,’ instead of a ‘.’
The comma is not a typo. Echo can take multiple strings as arguments. 🙂 http://php.net/manual/en/function.echo.php
What Stjepano says If you code for longer, you start to let go of niftyness and look more towards readability.
Using ternary operator wrong, indicates to me a lack of experience and/or youthful enthusiasm. If you use them:
– never nest ternary operators
– Store the result in a variable which is named after the result (Eg. $geniusStatusLabel = ($iq>120)?'genius':'below genius' ) and use the variable later.
– Be consistent in preferred value (if applicable). Eg. the following looks ackward $var = !isset($_POST['var'])?null:$_POST['var']
Question What is wrong with this code, I keep receiving an error.
Creating a sticky form and I am using a simple if (submit) then ( $_POST['value'] )
Please enter your short description of the category (blurb): Please enter a small description about this category.
Hey Dave!
I don’t use ternary very often, but is really nice in spots where things need to be tidy. I have a bit of a word of advice here on the use of ternary and collaboration. Dave addresses that in his points above, “Tips for Using Ternary Operators”. As a rule I use ternary only if the If/Else is a ‘single line of code’
Great article.
In the first example, I think it’s the same thing as doing :
$var_is_greater_than_two = ($var > 2);
Right ?
Technically yes, but the ternary operator lets you output whatever you want (i.e. a string “IT’S BIGGER!”, and not just true or false like in your example. This demonstrates how much more flexibility you get when using the ternary operator. 🙂
Good article, I’m glad some poeple cover this. One thing should be mentioned though – this should definitely not be used heavily. Embedded ternary operators, and nested ternary operators are a developer’s worst nightmare – it creates unnecessarily unreadable code that is difficult to maintain. Sometimes more code is better! 🙂
Thank you for this explanation. I have a background in Java so coming to PHP I see many similar coding between the two. This is one of them. But I wanted to make sure its the same in both and found you via Google when searching.
“Makes maintaining code quicker, easier” – I’d say that it’s quote contrary. It makes it more difficult and obscure, not easier (these statements are by far easier to accidentally skip or misunderstand while analysing the code than regular ifs).
if(1==$c) < $a=10; $b=12; >elseif(2==$c) < $a = 9; $b = 27; >elseif(3==$c)< $a=11; $b=8; >else
wish we had a syntax to test something and assign it to l_value if the test was successfull
like
y = x > 4 ?; means y = x if x > 4 or y = x > 4 ? : z; means y= x if x > 4 else y = z would be a shorthand for
y= x > 4 ? x : z Note usually when we test a condition on a variable we want to assign the same value as above then we could have y = x > 4 ? w : z; means y = w if x > 4 else y = z
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’;
Thanks for clarifying this only works from PHP 5.3+, I was getting nuts trying to figure it out why it wasn’t working.
$arg = 'T'; $vehicle = ( ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' ) ? 'airplane' : ( $arg == 'T' ) ? 'train' : ( $arg == 'C' ) ? 'car' : ( $arg == 'H' ) ? 'horse' : 'feet' ); echo $vehicle;
$arg = 'T'; echo $vehicle = ( ( $arg == 'B') ? 'bus' : (($arg == 'A') ? 'airplane' : (($arg == 'T') ? 'train' : (($arg == 'C') ? 'car' : (($arg == 'H') ? 'horse' : 'feet' )))));
Not all languages do things the same way. So you should never expect the same behavior in any of them. Though be pleasantly surprised is they are. For all other cases adapt your code accordingly.
string vehicle; string arg = "T"; vehicle = ( ( arg == "B" ) ? "bus" : ( arg == "A" ) ? "airplane" : ( arg == "T" ) ? "train" : ( arg == "C" ) ? "car" : ( arg == "H" ) ? "horse" : "feet" ); coutWhich is also usable in PHP in the same way. And both output the same result. This way if you want your code to be decently portable between languages, if that's a concern. Write it in a way that works either for both or decently for both.
Wow! I did not know that you don’t have to put a value after the question mark i.e. that you can do this:
var $myvar = 'Hello ' . $test ?: ' World';var $myvar = 'Hello ' . $test ? ' World' :;The ternary operator IS NOT the same as if/else; a ternary operator assures that a variable is given an assignment.
var xylophone; if (foo) < xylophone = 'bar'; >else < xylaphone = 'snafu'; //oops! and can be hard to spot >var xylophone = foo? 'bar' : 'snafu'; // a misspelling here is easier to spotI did want to add that in PHP ternary does not always make code shorter than a if/else. Given that you can code in similar if/else blocks to that of ternary. Many people are so hooked on the typical logic that if/else requires specifically if and else and brackets < >. Then when you do deeply nested ternary you then use ( ). Though with deeply nested if/else you can forgo the brackets, you can not with ternary. A deeply nested if/else simply understands the flow of logic without them. IE so many )))))))))); at the end of a deeply nested ternary. Which you can forgo in a deeply nested if/else, which the blow structure can also be a part of.
$a=3;$b=2; if($a>$b||die('Not Greater'))echo'Is Greater'; echo$a>$b?'Is Greater':die('Not Greater');$arg = 'T'; $vehicle = array( 'B' => 'bus', 'A' => 'airplane', 'T' => 'train', 'C' => 'car', 'H' => 'horse' ); echo $vehicles[$arg] ?: 'feet';Thanks for introducing me to this concept. It makes the code a lot shorter and once you are used to it even easier to read. I use this quite often now for example in this context:
$comments = $numComments>1 ? "Comments" : "Comment";$var_is_greater_than_two = ($var > 2 ? true : false); // returns true$var_is_greater_than_two = ($var > 2); // returns trueTechnically yes, but the ternary operator lets you output whatever you want (i.e. a string “IT’S BIGGER!”, and not just true or false like in your example. This demonstrates how much more flexibility you get when using the ternary operator. 🙂
I linked to it in my first post http://davidwalsh.name/php-shorthand-if-else-ternary-operators#comment-78632 > The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE. 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.
The ternary operator shouldn’t differ in performance from a well-written equivalent if/else statement…
The only potential benefit to ternary operators over plain if statements in my view is their ability to be used for initializationsYou mention in your article a list of advantages but you fail to mention the disadvantages. Also, one would argue that some of the claimed advatages are questionable. For example it can make maintaining the code slower and harder instead of quicker and easier if the expression in the ternary operator is not completely basic. Some other disadvantages.
– Code is more prone to cause a conflicts when merging changes from different developers.
– It makes debugging more difficult since you can not place breakpoints on each of the sub expressions.
– It can get very difficult to read
– It can lead to long lines of codePhp ternary operator short
315
311
8147
457
7229
18