I am trying to assign some value to one array if a condition is true otherwise I want to assign it to another array. I know this is possible with an if statement. However, I am wondering if it can be done with the syntax of a ternary operator?
Using an if statement it would look like this
if(condition){
$foo[] = $value;
} else{
$bar[] = $value;
}
However, my question is if it is possible to write it similar to this?
((condition) ? ($foo[]) : ($bar[])) = $value;
3
Answers
A statement like this will only result in a syntax error, or a fatal error:
You could also try to reference the but it still won’t work:
The if statement is probably your best option. However if you really want to do something like this, you could use a single associative array with
foo
andbar
just being keys:Yes you can but slightly different from the way you desire, like below:
First way is to assign value in each of the ternary blocks.
Online Demo
Second way is to use
array_push
like below:Online Demo
Note: Replace the
true
with your condition.Try this.
condition ? ($foo[] = $value) : ($bar[] = $value);