PHP If Loop
The If Loop is a very basic loop and used often. It’s used to check a condition and execute a code based on whether the condition was true or not.
if( … condition … ) {
… execute code …
}else{
… execute other code …
}
The condition is put between brackets and the code between accolades. The first code is only executed when the condition between brackets is valid ( true ), otherwise the 2nd code is executed.
For example:
$num = 1;
if($num == 1) {
echo “The variable num is equal to 1.”;
}else{
echo “The variable num is not equal to 1.”;
}
The above code will return:
The variable num is equal to 1.
Because $num == 1 is true and so the first code(the if-part of the loop) is executed. If num was not equal to 1 the 2nd code would have been executed ( the else-part of the loop ).
If you only want to execute a code if the condition is true, and don’t do anything if it isn’t, then you can leave out the else-part. Like this:
//execute a code if $num == 1
if($num == 1) {
echo “The variable num is equal to 1.”;
}
//otherwise do nothing
Sometimes, checking one condition is not enough. Therefore you can use else if -parts for your loop.
if($rank == “admin”) {
echo “Welcome Admin!”;
}else if($rank == “moderator”) {
echo “Welcome moderator!”;
}else if($rank == “guest”) {
echo “You’re not allowed to be here, guest!”;
}
The above code, for example, has multiple conditions. If the first condition is true, it will execute the first code between accolades, if the second condition is true, it will execute the second code between accolades, etc.. Do notice it will check the conditions in the order of how they’re written down. So it will first check the first condition and if that condition is true, it will not check the other conditions in the rest of the else if -parts anymore. It will only execute ONE ( or none ) of the codes between accolades. When multiple conditions may be true and so you want to check all the conditions and make it possible to have multiple codes executed, then multiple separate if loops should be used instead of the else if-parts.
It’s also possible to have multiple comparisions within one condition. These are the operators that may be used:
[TABLE=12]
And for comparing:
[TABLE=13]
The difference between == and = is that == is used to compare variables/values, and = is used to set a variable equal to a value.