Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.