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;
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.
true ? ($foo[] = $value) : ($bar[] = $value);
Online Demo
Second way is to use array_push like below:
array_push(${ true ? 'foo' : 'bar' }, $value);
Online Demo
Note: Replace the true with your condition.
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