Posts Tagged ternary
Ternary beauty
Posted by Ville Walveranta in Programming, Technical on 08 February 2010
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 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.
| | | copy code | | ? |
| 1 | |
| 2 | $b ? print "true" : print "false"; |
| 3 |
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:
| | | copy code | | ? |
| 1 | |
| 2 | $a = ($myObject->anotherObject->arr['somekey'] > 7 ? 7 : $myObject->anotherObject->arr['somekey']); |
| 3 |
You can do this:
| | | copy code | | ? |
| 1 | |
| 2 | $a = (($b = $myObject->arr['somekey']) > 7 ? 7 : $b); |
| 3 |
Awesome!!