17

I want to evaluate a simple ternary operator inside of a string and can't seem to find the correct syntax.

My code looks like this:

foreach ($this->team_bumpbox as $index=>$member) 
    echo ".... class='{((1) ? abc : def)}'>....";

but I can't seem to get it to work properly. Any ideas on how to implement this?

JonMorehouse
  • 1,313
  • 6
  • 14
  • 34
  • *String concatenation* if you want to use arbitrary expressions. In double quoted strings only simple variable and array syntax works, or variable expressions. Neither of which you have here. – mario Jan 04 '13 at 21:29
  • Presumably a real example doesn't have "1" as the conditional argument? – Oliver Charlesworth Jan 04 '13 at 21:29
  • yeah, real example would have a true expression. Just curious, as the syntax would look really nice imo :) – JonMorehouse Jan 04 '13 at 21:30
  • 1
    Exactly how is PHP supposed to know that something inside a string is actually php code? That's **YOUR** job to tell it. – Marc B Jan 04 '13 at 21:33

2 Answers2

30

You can't do it inside the string, per se. You need to dot-concatenate. Something like this:

echo ".... class='" . (1 ? "abc" : "def") . "'>....";
svidgen
  • 13,744
  • 4
  • 33
  • 58
6

Well, you can do it actually:

$if = function($test, $true, $false)
{
  return $test ? $true : $false;
};

echo "class='{$if(true, 'abc', 'def')}'";

I'll let you decide whether it is pure elegance or pure madness. However note that unlike the real conditional operator, both arguments to the function are always evaluated.

IS4
  • 11,945
  • 2
  • 47
  • 86