How can I set one variable to true based on other conditions. Here, instead of doing
if ($vara && $varb && $varc)
I’m something like below. Problem is, I’m just not getting something right. Can you please help me?
<?php
$onward = false;
$vara = 11;
$varb = 21;
$varc = 3;
if ($vara == 1)
{$onward = true;}else{$onward = false;}
if ($varb == 2)
{$onward = true;}else{$onward = false;}
if ($varc == 3)
{$onward = true;}else{$onward = false;}
if ($onward)
{
echo "Ok";
}else {echo "Not ok";}
?>
Each of your conditions ignores the result of the previous condition. You need to include the previous state of
$onwardin each subsequent test:This way,
varbandvarcare only tested if$onwardis still true after the previous test.This is a particularly ugly way of writing code. If you have three large conditions and you don’t simply want to join them on one line as in your
$vara && $varb && $varc, you should be writing it this way:Any time you’re simply returning/setting something to true/false in the branches if your if statement, you should just be returning/setting the condition itself.
That is, this:
should always be written: