Jump to content

Archived

This topic is now archived and is closed to further replies.

johnnyk

Ternary Operator

Recommended Posts

Is it possible to use a ternary operator on the same line as an echo (using the conditional to modify the echo)?

Share this post


Link to post
Share on other sites
Yes; try it out.

[code]
<?php
    echo 0 ? 'true' : 'false';
?>
[/code]

Share this post


Link to post
Share on other sites
My fault for not making myself clear. What I mean is is it possible to use a ternary operator in the middle of an echo?

Something that would mimic:
[code]
echo 'You have';
if($a >= 4){
   echo 'equal to or more than 4';
}else{
   echo 'less than 4';
}
echo "items<br />\n";
[/code]

I can't find a way to do that with ternary operator (without including the whole phrase, You...items, on each evaulation of the conditional).

Share this post


Link to post
Share on other sites
You might have to use parantheses to make it unambiguous, but, yes:[code]echo "You have " . ($a < 4 ? 'less than four' : 'four or more') . " items.";[/code]

Share this post


Link to post
Share on other sites
[!--quoteo(post=385797:date=Jun 19 2006, 05:11 PM:name=Wildbug)--][div class=\'quotetop\']QUOTE(Wildbug @ Jun 19 2006, 05:11 PM) [snapback]385797[/snapback][/div][div class=\'quotemain\'][!--quotec--]
You might have to use parantheses to make it unambiguous, but, yes:[code]echo "You have " . ($a < 4 ? 'less than four' : 'four or more') . " items.";[/code]
[/quote]
It's not working for me.

echo '<h5 class="class">' . $row['a'] . ((isset($row['b'])) ? 'text') . "</h5><br />\n"; //line 30
is producing
Parse error: syntax error, unexpected ')' in page.html on line 30

Share this post


Link to post
Share on other sites
[!--quoteo(post=385800:date=Jun 19 2006, 05:22 PM:name=JohnnyK)--][div class=\'quotetop\']QUOTE(JohnnyK @ Jun 19 2006, 05:22 PM) [snapback]385800[/snapback][/div][div class=\'quotemain\'][!--quotec--]
It's not working for me.

echo '<h5 class="class">' . $row['a'] . ((isset($row['b'])) ? 'text') . "</h5><br />\n"; //line 30
is producing
Parse error: syntax error, unexpected ')' in page.html on line 30
[/quote]

That's because your code snippet is missing the rest of the ternary operator (the colon part); if you don't need a false condition, at least put an empty string:
[code]... . (isset($row['b']) ? 'text' : '') . ...[/code]
PHP is expecting that, instead it's running into an "unexpected parenthesis."

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.