Reputation: 549
Trying to return the value of either $dy or $days. Sometimes $dy is set, other times $days is set.
For example: $dy['value'] = 45 or $days['value'] = 75 (only one value will be set)
However when I execute this statement the value is always equal to 1. How can I return the actual value of either $dy or $days.
$days = isset($dy['value']) || isset($days['value']) ? ($dy['value'] || $days['value']) : null;
Upvotes: 0
Views: 162
Reputation: 29012
About 1
:
In PHP, ||
doesn't do what you might expect coming from JavaScript, because the result will always be a boolean. ||
implicitely converts its operands to booleans and returns the result.
To get the equivalent of a short-circuit ||
from JavaScript in PHP, you can use ?:
(the so-called "Elvis operator" - x ?: y
is a shorthand for x ? x : y
):
$days = isset($dy['value']) || isset($days['value']) ? ($dy['value'] ?: $days['value']) : null;
I didn't change the first ||
because it's indeed a boolean operation, but I did replace the second.
However I think there is a logic error in your code anyway, because if you have E_NOTICE
error reporting on, PHP will complain anyway if $days['value']
is set and $dy['value']
isn't, because you are still accessing $dy['value']
even if isset($dy['value']) == false
. So you would need to use, for example:
$days = (isset($dy['value']) ? $dy['value'] : null) ?: (isset($days['value']) ? $days['value'] : null);
(Assuming you also want to skip a value if it's falsy - according to how you are using the ||
it looks like it.)
If you don't care about notice errors at all (discouraged!) you could just use:
$days = $dy['value'] ?: $days['value'] ?: null;
Upvotes: 1
Reputation: 119
I guess This might be what you wanted:
$days = (isset($dy['value']) || isset($days['value'])) ? (isset($dy['value'])?$dy['value'] : $days['value'])) : null;
Upvotes: 0
Reputation: 10447
Any particular reason you need a ternary? In this case an if elseif would probably be cleaner and easier to read.
if ( isset($dy['value']) )
{
$days = $dy['value'];
} elseif ( isset($days['value'] )
{
$days = $days['value'];
}
If it absolutely must be a ternary, you need a ternary within a ternary:
$days = isset($dy['value']) ? $dy['value'] : (
isset($days['value']) ? $days['value'] : null
);
If you're using PHP 5.3+ (which you should be) this should work to:
$days = $dy['value'] ?: ( $days['value'] ?: null );
Upvotes: 0