Page 1 of 1
Ternary Operator Question
Posted: Mon Aug 13, 2007 6:19 pm
by toasty2
Lately, for short and sweetness I've been using the ternary operator for only caring about one of the two conditions (either just true or just false), like:
Is there anything wrong with that? If that's fine to do, what should I put as the do-nothing code...in that example I just put "false", what would you do?
Posted: Mon Aug 13, 2007 7:53 pm
by superdezign
You should only use ternary conditions if you have an outcome for when the condition is true and one for when it is false.
Posted: Mon Aug 13, 2007 7:59 pm
by Benjamin
Looks like a bad habit to get into to me. All you need is 1 if statement, no else.
When I see that it makes me wonder what the rest of your code looks like.
You could use..
or even better..
Code: Select all
// force $foo to be set because [your reason here]
if (empty($foo))
{
exit();
}
Posted: Mon Aug 13, 2007 8:19 pm
by toasty2
superdezign wrote:You should only use ternary conditions if you have an outcome for when the condition is true and one for when it is false.
I know thats its purpose, but it works if for one of the outcomes I just put "filler code" (that doesn't do anything). There isn't anything wrong with that is there?
I'm not opposed to if statements, but I like the shortness of ternary.
Posted: Mon Aug 13, 2007 8:22 pm
by Benjamin
Yes
Posted: Mon Aug 13, 2007 8:24 pm
by superdezign
toasty2 wrote:I know thats its purpose
Then why use it otherwise?
Posted: Mon Aug 13, 2007 8:26 pm
by toasty2
Alright, fine.

Posted: Mon Aug 13, 2007 11:18 pm
by Z3RO21
toasty2 wrote:I'm not opposed to if statements, but I like the shortness of ternary.
The if method appears to be shorter than you ternary one.
Posted: Tue Aug 14, 2007 4:19 am
by stereofrog
If you're interested in writing shortcuts to the IF operator, try boolean arithmetics
Code: Select all
# exit IF condition is true
empty($someVar) && exit;
Code: Select all
# exit UNLESS condition is true
empty($someVar) || exit;
The latter is widely known from the notorious "or die" idiom.
The key difference of shorcuts (including ternary) compared to the normal IF is that you cannot use any statements, only expressions.
Posted: Tue Aug 14, 2007 4:35 am
by CoderGoblin
Comes down to personal taste. Ternary can be useful in places but many people find it harder to read (no IF to read and recognise). I tend to use them only where I need to output one thing or another based on a variable. Most other cases I use a normal if. An example of the use of the ternary below.
Code: Select all
echo $count.' User'.($count==1 ? '' : 's').' have done this';
rather than
Code: Select all
if ($count==1) {
echo $count.' User have done this';
} else {
echo $count.' Users have done this';
}
In the example being given I would use
Code: Select all
if (empty($foo)) exit(); // exit when foo empty