$val1 = false;
$val2 = 10;
$variable = $val1 || $val2;
开发者_如何学编程
the code above makes $variable = true
.
Is there any operator in PHP that would make $variable
take the value of $val2
, if $val1
is false?
I thought ||
would do this, but it only returns true if any of the values are true, or false if both are false...
The ternary operator
$variable = ($val1) ? $val1 : $val2;
or (in PHP 5.3+ )
$variable = ($val1) ?: $val2;
The operator ||
does a logical or, that's why you only get true or false back.
You might want to use PHP ternary operator:
$variable = $val1? "default value" : $val2;
You can also absue operator precedence:
$variable = $value1 or $variable = "value2";
or
is weaker than =
. It gets more readable if you add extra spaces. But it's more or less a workaround for the lack of ?: in PHP<5.3.
精彩评论