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 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');/* 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.
Comments
Be Heard!
Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!
Nice job clarifying this! I keep forgetting the exact syntax for some reason…
Your second echo example in the more examples is missing the first ‘e’ in the code.
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;
I’ve been looking for a good explanation of this, thank you.
Now I’m off to scour my code for opportunities to practice.
ohh wow man, i really needed this
thanks for sharing that with such nice explanation
thanks again
@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
These are nice shorthands, but be warned, it will make your code unreadable and less understandable.
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):
<textarea id="catblurb" name="catBlurb" value="
">
Please enter a small description about this category.
I only need the if part of the if/else.
Thanks for any help
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’ <— Yes this is variable depending on screen size. Just don't go overboard when working collaboratively or if there is a chance some-one else will inherit the code.
Great article.
In the first example, I think it’s the same thing as doing :
$var_is_greater_than_two = ($var > 2);
Right ?