PHP Conditional Statements
Like most programming languages, PHP also allows you to write code that performs different actions based on the results of logical or comparative test conditions at run time. This means you can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions.
There are several statements in PHP that you can use to make decisions:
- The if statement
- The if…else statement
- The if…elseif….else statement
- The switch…case statement
PHP – The if Statement
The if the statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest of PHP’s conditional statements and can be written like:
Syntax:
if (condition) {
code to be executed if condition is true;
}
The following example will output “Have a nice weekend!” if the current day is Friday:
Example:-
The if…else Statement
You can enhance the decision making process by providing an alternative choice through adding an else statement to the if statement. The if…else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this:
Syntax:-
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
The following example will output “Have a nice weekend!” if the current day is Friday, otherwise it will output “Have a nice day!”
Example=>
The if…elseif…else Statement
The if…elseif…else a special statement that is used to combine multiple if…else statements.
Syntax:
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
The following example will output “Please Enter Valid Percentage”
Example=>
you will learn about PHP switch-case statement in the next Blog
- Best AI tools for Software Engineers - November 4, 2024
- Installing Jupyter: Get up and running on your computer - November 2, 2024
- An Introduction of SymOps by SymOps.com - October 30, 2024