PHP 5.3 and The Ternary Shortcut
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.
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.
Comments
It’s a shame that certain error levels will still throw notices and warnings when testing a key that may not exist on an array, because if it’s convenient to save typing an extra “1″ or “true” and a few spaces, it’d be *extra* convenient to be able to write something like:
$status_level = $_POST['status_level'] ?: null;
rather than:
$status_level = isset($_POST['status_level']) ? $_POST['status_level'] : null;
I recognize a lot of us have gotten around this by tuning down error levels, or writing our own functions to deal with this more smoothly, or turning to IDEs that get around limitations like this. But you can’t tune error levels everywhere, writing your own functions has runtime costs, and the IDE stuff is bandaids.
Sorry to rant. This has been a burr in my PHP saddle for a long time. I think the new feature’s a good edition, but it seems penny-wise and pound-foolish to add it without dealing with the problems notices on non-existant keys produce.




Thank you so much for this article. It really helps in making code easier to read and overall is easy to use.
Great article