PHP if else
PHP Conditional Statements
The core functionality of PHP can evaluate expressions and perform an action based on the results, and If statements are a simple way to do that.
If statement is the most basic conditional statement in PHP, it is like the English language sentence "If this happens, do that." It works like this.
Output:
There are three ways we can write the if statement.
Output:
PHP - The if Statement
An if statement compares an expression of two values with an operator, and it evaluates to a true or false value. A simple if statement looks like this.
$x = 15; $y = 20;
if( $x == $b) {
echo "$x and $y both are equal ";
}
PHP - The if...else Statement
If you want to execute a code when an expression returns a true value and another code when an expression returns a false value, then consider using the else if-else statement.
$x = 15; $y = 20;
// Comparing the value if variables ignoring the data types.
if( $x == $b) {
echo "$x and $y both are equal ";
} else {
echo "$x and $y are not equal";
}
PHP The if...elseif...else Statement
If you want to test a variable against multiple values and take different actions for each outcome, you can use an else-if statement.
Output:
The variable $today holds the day name, which is Friday, and the PHP else if statement is checking whether it is a working day or off day.
One thing to remember is that if-elseif-else construct does not execute the rest of the code as soon as one of the conditions evaluates to true. It skips the remaining expressions and executes the code next to the if-elseif-else statement.