[ACCEPTED]-Conditional operator with only true statement-conditional-operator
It doesn't get much shorter than:
if($condition) $var = $value;
0
IMO, the best way to make your code sample 6 shorter is:
if($myarray["foo"] == $bar)
$variablename = $myarray["foo"];
FYI, the name of the operator 5 you're asking about isn't "the ternary 4 operator", it's the conditional operator.
Since you ask, a way 3 you could actually use the conditional operator 2 to do what you're asking is:
$myarray['foo'] == $bar ? $variablename = $myarray['foo'] : null;
but that's somewhat 1 horrifically ugly and very unmaintainable.
You could do this, but I wouldn't as it 1 is pretty unreadable and stupid:
$myarray["foo"] == $bar ? $variablename = $myarray["foo"] : 0;
or
$myarray["foo"] == $bar && $variablename = $myarray["foo"];
Your right, ternary is not the way to go. It's 3 there to handle the if and else part of 2 the statement.
Just stick with the regular 1 if statement.
if($myarray["foo"]==$bar) $variablename=$myarray["foo"];
The "problem" you have isn't really a problem. Your 10 example code is very clear and maintainable. I 9 would really say leave it like it is.
You 8 -could- remove the braces, but that will 7 have an impact on maintainability.
Your other 6 alternative is to create a set_if_true(mixed 5 array, string key, boolean conditional) wrapper 4 function. It hides what is really happening 3 but depending on your specific implementation 2 it is a good option. (For instance a configuration 1 type object, or caching backend)
Put !=
instead of ==
and ?:
instead of just ?..
$variablename = ($myarray["foo"] != "bar") ?: $myarray["foo"];
is 2 the same as
if($myarray["foo"] != "bar"){} else { $variablename = $myarray["foo"]; }
It might not be the smartest 1 solution but it works. I like this one more
if($myarray["foo"] != "bar") {$variablename = $myarray["foo"]};
Set the variable to itself in the false 1 case:
$variablename=($myarray["foo"]=="bar")? $myarray["foo"] : $variablename
You can put the original expression in the 4 else
part of the ternary operation, but if you 3 want to guarantee single evaluation of the 2 expression then you'll have to use a temporary 1 variable and an if
statement.
Ternary isn't the way, even though it can 4 be written so that ternary works.
The reason 3 is this: you're trying to use it in a way 2 it's not intended, which will make your 1 code awkward for other developers to read.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.