I recently came across a bug in some code at work where a series of function calls were aggregated into a single success condition. Something like
$success = true;
foreach($foo as $f) {
$success = $success && do_foo($f);
}
The bug is do_foo() was intended to run across the entire collection (it has side-effects). but the && operator short-circuts and once once a false is encountered do_foo isn't called on the remainder of the collection. Easy enough to refactor, but it led me to wondering:
Does PHP have a logical operator that does not short-circut?
Edit: Let me be clear, I'm not asking how to solve the bug. This is a hypothetical question about syntax.
There's no dedicated operator for this purpose, but you have the choice of doing whacky stuff like this (assuming do_foo($f)
always returns a boolean:
$success &= do_foo($f);
The outcome will be a numeric 0 or 1 instead of a boolean, but when used in a condition it shouldn't matter.
If the function doesn't always return a boolean or if the above is too unsettling:
$success = (bool)($success & do_foo($f));
That said, do_foo($f)
should be run unconditionally and its return value used in the next statement.