Reputation: 21
A coworker frequently uses PHP's ternary operator as a control structure, rather than the RHS of an expression. One such example:
list==''?list=val:list=list+','+val;
(In that example, the statement is called in a loop to add values to a string, ensuring the comma separator doesn't appear if there's only one item.) In essence, he relies on the expression evaluation to do work, and throws away the expression result.
Aside from the fact that it's hard on the eyes, is there any reason to avoid this construct? It's syntactically legal; and it executes correctly. But I'm certain the ternary operator wasn't designed to be used in this manner, and I wonder if there are consequences to doing so.
Upvotes: 2
Views: 168
Reputation: 116140
It will work fine, and I don't see any problem with it apart from readability.
If you think it's hard on the eyes, replace this loop and line with a call to the implode
function.
Upvotes: 3