Ternary Operators Anyone?

While reading through the WordPress Coding Standards, I read some good advice to follow when using ternary operators.

To keep things from getting confusing when using ternary operators, always have the statements test for true instead of false.

// (if statement is true) ? (do this) : (if false, do this);
$basketballteam = ( 'lakers' == $team ) ? 'champions' : 'blah';

In the example above, you’ll notice that the variable is on the right side of the comparison. This way, if an equal sign is omitted, a parse error will be thrown and execution will halt. If you can save one bug, do it. ๐Ÿ˜‰

One thought on “Ternary Operators Anyone?”

  1. You’ve actually got two tips mixed into one there.

    The first is to make the conditional part of a ternary operator test for truthness – so, don’t start including negation operators ( ! ) in there; if that’s needed, just swap the 2nd and 3rd parts.

    Your second (and separate) tip is to keep equality (and identity) testing with strings and integers on the left side, for the reasons you identified.

Comments are closed.