...

View Full Version : Can somebody help me break down this 1 line of code ??



mOrloff
02-17-2010, 10:18 PM
I'm reviewing someone elses code, and came across this line:


<?php echo ($view=='folded')? 'folded_form_step':'form_step';?>


There are several things I'd like to learn here.

For starters, what is ($view=='folded')? all about? This is the first time I've seen anything like that. Is that shorthand for an IF statement or something ?
Next, what's with the : (colon)?

Can someone walk me through what's being done here ??

FYI: this is in a class which builds forms, and $folded_form_step & $form_step are vars which get passed into the class, but the code in question does not use the dollar signs. Are they related?

~ Mo

Fou-Lu
02-17-2010, 10:23 PM
Ternary operator.
($view == 'folded') <- Indicates a condition. Techincally the brackets are not required
? expression <- What to do if its true
: expression <- What do to if its false

In 5.3 (I think its 5.3 it was introduced) you can actually do a shorthanded ternary for just the else:
($d == 'data') ?: 'no match';


echo ($view=='folded')? 'folded_form_step':'form_step';
// is the same as
if ($view == 'folded')
{
echo 'folded_form_step';
}
else
{
echo 'form_step';
}

Dormilich
02-17-2010, 11:14 PM
In 5.3 (I think its 5.3 it was introduced) you can actually do a shorthanded ternary for just the else:
($d == 'data') ?: 'no match';
the true case returns the evaluation of the condition. i.e. this code would return 1 if $d = "data".

mOrloff
02-18-2010, 12:10 AM
Ahah!

Thanks-a-bunch.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum