Ternary Operator Inside PHP String
Asked Answered
E

2

20

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?

Emulous answered 4/1, 2013 at 21:27 Comment(4)
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.Coonhound
Presumably a real example doesn't have "1" as the conditional argument?Bobbibobbie
yeah, real example would have a true expression. Just curious, as the syntax would look really nice imo :)Emulous
Exactly how is PHP supposed to know that something inside a string is actually php code? That's YOUR job to tell it.Muckrake
P
33

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

echo ".... class='" . (1 ? "abc" : "def") . "'>....";
Phosphoresce answered 4/1, 2013 at 21:31 Comment(0)
C
7

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. Once you can evaluate arbitrary functions however, there is nothing stopping you from using this with any general expression:

$expr = function($x)
{
  return $x;
};

echo "class='{$eval(true ? 'abc' : 'def')}'";
Crusade answered 21/3, 2021 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.