Thursday, August 2, 2012

PHP Shorthand If/Else Using Ternary Operators (?:)

I always forget this trick when I need it. A great shortcut to keep on hand for those quick if/else needs.

An essential part of programming is evaluating conditions using if/else and switch/case statements. If / Else statements are easy to code and global to all languages. If / Else statements are great but they can be too long.

I preach a lot about using shorthand CSS and using MooTools to make JavaScript relatively shorthand, so I look towards PHP to do the same. If/Else statements aren’t optimal (or necessary) in all situations. Enter ternary operators.

Ternary operator logic is the process of using “(condition) ? (true return value) : (false return value)” statements to shorten your if/else structures.

via PHP Shorthand If/Else Using Ternary Operators (?:).

No comments: