Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator Inside PHP String

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?

like image 870
JonMorehouse Avatar asked Jan 04 '13 21:01

JonMorehouse


People also ask

Can we use ternary operator in PHP?

The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.

How ternary operator used in PHP explain with example?

ternary operator: The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right.

Is ternary operator faster than if in PHP?

The right answer is: it depends. Most of the time, they are about the same speed and you don't need to care. But if $context['test'] contains a large amount of data, snippet 2 is much faster than snippet 1.

What is shorthand operator in PHP?

The shorthand ternary operator In this syntax, PHP evaluates $initial in the boolean context. If $initial is true, PHP assigns the value of the $initial to the $result variable. Otherwise, it assigns the $default to the $result variable.


2 Answers

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

echo ".... class='" . (1 ? "abc" : "def") . "'>....";
like image 112
svidgen Avatar answered Oct 19 '22 08:10

svidgen


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.

like image 7
IS4 Avatar answered Oct 19 '22 07:10

IS4