As you all might know PHP 5.3 alpha 1 was released not to long ago and people are still wondering what this “Ternary Shortcut” is all about. In this article you will understand its basic usage in a real application.
So how does it work?
Basically the new ternary shortcut is used as a true or false statement. Back with the old ternary statement, it took 4 sections which:
- Assigned to a variable (When we assign the ternary to a variable)
- Did a “IF” statement
- Return Clause 1 (Which if the “IF” statement is true return this value else return clause 2)
- Return Clause 2
Looks Like: $var = ( expression ) ? (clause 1) : (clause 2);
The Ternary looks like it doesn’t work like that, it takes 3 sections:
- Assigned to a variable
- Do a “IF” statement” (Return 1 else return clause 2)
- Return Clause 2
Looks Like: $var = ( expression/clause 1) ?: (clause 2);
When would I use it?
This question came up to me a few times from a few friends and they asked, when would I use this. Well the best place to use this in your scripts are for options that contains checkboxes.
Why Check Boxes?
Well as I stated above, The Shortcut Ternary feature is basically a yes or no (or on or off) feature, and usually checkboxes are used for “on” and “off” features. We could use a ternary statement like the following:
$website_offline = isset($_POST['website_offline']) ?: 0;
Basically what I did there was if the input checkbox was set then it would return 1 else if it wasn’t set it would return 0.
I hope this clears up things with future developers. If you would like to elarborate on this article please feel free to comment.
Topics: Design, PHP, Programming
Submit Your Article






