Reputation: 1411
I know PHP uses lazy-evaluation / short-circuit operators. But say I wanted to evaluate all the expressions in a condition, for example:
$a = "Apple";
$b = "Banana";
$c = "Cherry";
function check($fruit) {
if ($fruit != "Banana") {
echo "$fruit is good.\n";
return true;
} else {
echo "$fruit is bad.\n";
return false;
}
}
if (check($a) && check($b) && check($c)) {
echo "Yummy!\n";
}
Because of lazy-evaluation, this will only output:
Apple is good.
Banana is bad.
Rather than the desired output of:
Apple is good.
Banana is bad.
Cherry is good.
This is useful in form validation for instance.
So my question: Is there any way to force all expressions in a condition to be evaluated in PHP, and if not, what would be the best/quickest way to get the desired result in the example above?
Upvotes: 1
Views: 127
Reputation: 1058
function check($fruit) {
echo ($fruit != "Banana") ? "$fruit is good.\n" : "$fruit is bad.\n";
return $fruit != "Banana";
}
$a = "Apple";
$b = "Banana";
$c = "Cherry";
if (check($a) & check($b) & check($c)) {
echo "Yummy!\n";
}
/*
Apple is good.
Banana is bad.
Cherry is good.
*/
$a = "Apple";
$b = "apple";
$c = "Cherry";
if (check($a) & check($b) & check($c)) {
echo "Yummy!\n";
}
/*
Apple is good.
apple is good.
Cherry is good.
Yummy!
*/
Upvotes: 0
Reputation: 41833
You can use bitwise AND (single ampersand: &
)
$a = "Apple";
$b = "Banana";
$c = "Cherry";
function check($fruit) {
echo ($fruit != "Banana") ? "$fruit is good.\n" : "$fruit is bad.\n";
}
if (check($a) & check($b) & check($c)) {
echo "Yummy!\n";
}
Prints:
Apple is good.
Banana is bad.
Cherry is good.
Example: http://sandbox.onlinephpfunctions.com/code/07092a9d6636ae8ddafce024d7cc74643e311e9c
Upvotes: 1