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?
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.
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.
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.
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.
You can't do it inside the string, per se. You need to dot-concatenate. Something like this:
echo ".... class='" . (1 ? "abc" : "def") . "'>....";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With