Jump to content

Ternary Operator


johnnyk

Recommended Posts

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).
Link to comment
https://forums.phpfreaks.com/topic/12413-ternary-operator/#findComment-47463
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
Link to comment
https://forums.phpfreaks.com/topic/12413-ternary-operator/#findComment-47467
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."
Link to comment
https://forums.phpfreaks.com/topic/12413-ternary-operator/#findComment-47468
Share on other sites

Archived

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

×
×
  • Create New...

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.