Features like namespacing aside, one of the parts of PHP 5.3 that had me initially more excited was the ability to shorten tenary statements even further. I know, some of you are anti ternary all together, but personally I love it. First, a quick refresher. This is an annoying bit of code for one variable check:

<?php
 
if (empty($_POST['action']))
{
	$action = 'default';
}
else
{
	$action = $_POST['action'];
}
 
?>

Not only is it a lot of code, but its just bad practice to create new (and potentially widely used) variable while enclosed in an if statement. Ternary gives us the ability to shorten the above to this:

<?php
 
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
 
?>

The previous two pieces of code are identical in functionality. If the above can be referenced to as (expr1) ? (expr2) : (expr3), PHP 5.3 says that expr2 may be removed to give us an even less repetitive bit of code. The problem here, is this new feature is nearly useless. expr1 has to return true or false, so the variable that we’re evaluating has to exist. Given the two above examples, the logical natural progression in perhaps not logic but making our code more efficient would be:

<?php
 
// This MIGHT error
$action = ($_POST['action']) ?: 'default';
 
?>

However the above example is very not advisable. If the “action” key does not exist in $_POST, you have yourself an error. Its a dangerous assumption to make, especially considering were “action” a checkbox and left unchecked, it certainly would not exist. It seems to me that if they had made it work more like the empty function, this shortcut would be infinitely more useful than it is now. Its ironic that not only the best ternary usefulness example that I could come up with involved $_POST and empty(), but php.net also exemplifies with the same thing. The one time this shortcut would be the most useful is the time it cannot be used.

But wait! There is a work around to this! Credit John Squibb for coming up with this (hacky) gem:

<?php
 
$action = @($_POST['action']) ?: 'default';
 
?>

The “@” symbol tells PHP to suppress any error that may result of the line it precedes, thus making this work as desired. Personally I usually am very against using it, but this may be a nice exception (pun!). How dirty you want to feel is up to you.

Tagged with:
 

One Response to PHP 5.3 Ternary Shortcut Functionality (or lack thereof)

  1. [...] previously discussed , the new ternary shortcut is very short and handy, but is practically useless in every day [...]

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.