php - How to assign first non false variable from a group of them -
i tried way without effect:
$a = false; $b = false; $c = 'sometext'; $result = $a or $b or $c or exit('error: variables false');
and $result should set $c, gives value of bool(false)
instead.
there's couple of things going on here:
firstly, in php result of boolean operation boolean.
secondly, , more subtly, "english" boolean operators (or
, and
) have low precedence - lower assignment operator, =
.
therefore in expression $result
actual value of $a (regardless of $a
's value), since assignment applied before boolean operator.
// has same effect: $result = $a or $b or $c; // this: $result = $a; $a or $b or $c; // has no effect
this confusing, , not want.
to boolean result of whether of $a
, $b
, $c
truthy (ie true
, or castable true
) can either use parentheses force precedence, or use "c-style" operators (||
, &&
) have higher precedence:
// these have same effect: $result = ($a or $b or $c); $result = $a || $b || $c; if ($a or $b or $c) $result = true; else $result = false; if ($a || $b || $c) $result = true; else $result = false;
if you're unsure operator precedence it's best use parentheses - tend make code more readable, since order of evaluation made more obvious.
it's better not rely on implicit type conversions (especially casting non-numeric strings), since tends make unclear code.
edit:
to answer actual question, approach (though don't recommend in case, since you're interested in first non-false value) use array_filter
without callback - return array of all values in input array truthy, keys preserved.
eg:
$a = false; $b = false; $c = 'sometext'; $result = array_filter(array($a, $b, $c)); var_dump($result);
outputs:
array(1) { [2]=> string(8) "sometext" }
Comments
Post a Comment