This code is executed if the condition is true
else
This code is executed if the condition is false
For example
The following example will give the result "Happy weekend!" If today is Friday. If not, it will result in "Have a happy day!":
Save the above program in a file named test.php in htdocs , then open the browser and type the address http:/// localhost: 8080 / test.php will result:
If you want to execute a code block if one of the conditions is true, then you should use the elseif command in PHP.
Syntax
if (thing_kien_1)
This code is executed if condition 1 is true;
elseif (thing_kiện_2)
This code is executed if condition 2 is true;
else
This code is executed if the conditions are false;
For example
The following example will give the result "Happy weekend!" If today is Friday, and "Happy Sunday!" If today is Sunday. If not, it will result in "Have a happy day!":
Save the above program in a file named test.php in htdocs , then open the browser and type the address http:/// localhost: 8080 / test.php will result:
If you want to select one of the many code blocks to be executed, you should use the switch command in PHP. The switch command is used to avoid if . elseif . else blocks.
Syntax
switch (expression)
{
case label_1:
This code is executed if the expression = label_1
break;
case label_2:
This code is executed if the expression = label_2
break;
.
default:
This code is executed if
expression_ is different from label_1, label_2, .
}
For example
The working mechanism of the switch command is excellent. First, it evaluates the given expression, then finds a label to match the estimated result value. If a match is found, the code associated with the label will be executed or if there is no matching label, the command will execute any given default code block.
Save the above program in a file named test.php in htdocs , then open the browser and type the address http:/// localhost: 8080 / test.php will result:
Follow tutorialspoint
Previous article: Operator in PHP
Next article: Loop in PHP