I want to add value to multiple variable If condition shorthand but I don't know how to use symbol split between 2 variable
eg. manuscript
if(condition) {
$var1 = "a";
$var2 = "b";
} else {
$var1 = "";
$var2 = "";
}
Shorthand [error]
(condition) ? $var1 = "a", $var2 = "b"
: $var1 = "", $var2 = "";
Don't do it. The if
statement is fine. It's simple and clear. Try to cram multiple assignments into the ?:
ternary operator, next thing you know you're hacking Perl scripts for spare change in some back alley.
I would write exactly what you have:
if (condition) {
$var1 = "a";
$var2 = "b";
} else {
$var1 = "";
$var2 = "";
}
You could potentially write it like this, if you prefer. This is a good choice if you first assign default values and the if
condition assigns less common values.
$var1 = "";
$var2 = "";
if (condition) {
$var1 = "a";
$var2 = "b";
}
If you really want to use the ternary operator you could write this, if you're okay writing condition
twice:
$var1 = condition ? "a" : "";
$var2 = condition ? "b" : "";