Hi,
I know that we can write IF-ELSE statement in one line, such as,
$eatit = ($applet !="gree") ? "Eat" : "Dont Eat";
but how about IF-ELSEIF-ELSE statement??
how do I write these into one line?
if(isset($cat_name))
{
$page_path = 'blog/categories/'.$cat_name;
}
elseif(isset($pg_archive))
{
$page_path = 'blog/archive/'.$pg_archive ;
}
else
{
$page_path = home';
}
many thanks,
Lau
Try this:
$page_path = (isset($cat_name) ? 'blog/categories/'.$cat_name : ((isset($pg_archive) ? 'blog/archive/'.$pg_archive : 'home')));
Personally, I think the readability of nested ternary statements suck. It’s not that I can’t understand them, but rather I can clearly read an if/elseif/else statement pretty much instantly, but most nested ternary statements, I need to look at for a moment.
They suck less if you spread it out over a few lines and indent it, but might as well use if/elseif/else then, and it will be easier to modify if ever needed.
crmalibu:
Personally, I think the readability of nested ternary statements suck. It’s not that I can’t understand them, but rather I can clearly read an if/elseif/else statement pretty much instantly, but most nested ternary statements, I need to look at for a moment.
They suck less if you spread it out over a few lines and indent it, but might as well use if/elseif/else then, and it will be easier to modify if ever needed.
thanks for your input. i prefer multiple lines personally as they are easier to understand
Vali
May 13, 2010, 7:31pm
6
I hope I’ll never have to work after you two…
While I agree that it is very terse, reminds me of Perl, I would never use a nested ternary.
I only posted it because that is what he asked for. I did not question his motives.
Vali
May 14, 2010, 2:15pm
8
In perl is not that messed up…
my $var = shift || 'default';