Ternary beauty

I love the ternary operator. It can often simplify a much more complex conditional into few characters. In PHP (and other c-like languages) it’s possible to do all sorts of things with the ternary. The following are examples from PHP.

If $b is true, print “true”, otherwise print “false”. Echo doesn’t work here.

$b ? print "true" : print "false";

Here’s something I learned today: it’s possible to assign a complex variable to an “internal” shorthand, and then in turn use the shorthand for the final assignment (based on the comparison). This way it’s not necessary to repeat the complex variable in the assignment section which makes the ternary much shorter and thus cleaner.

So instead of this:

$a = ($myObject->anotherObject->arr['somekey'] > 7 ? 7 : $myObject->anotherObject->arr['somekey']);

You can do this:

$a = (($b = $myObject->arr['somekey']) > 7 ? 7 : $b);

Awesome!! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.