PHP If & Else statement
Conditional statements help you to make a decision based on certain conditions if else and else if will only be considered exactly the same when using curly brackets. When using a colon to define your if/else if conditions, you must not separate else if into two words.
- if statement - executes some code condition if one condition is true
- if...else statement - executes some code condition if a condition is true and another code if that condition is false then execute else part.
- if...else if...else statement - executes different codes for more than two conditions
- switch statement - selects one of many blocks of code to be executed any one code condition or default
The PHP If statement
The if statement executes some code if one condition is true. if condition is false then not code executes
Syntax:
if (condition) {
some code to be executed if condition is true;
}
Example:
<?php
$age = 10;
if ($age < 20) {
echo " Welcome ! this condition is true ";
}
?>
The PHP If ..else.. statement
The if statement executes some code if one is true. if condition is false then execute else part code
Syntax:
if (condition) {
some code to be executed if condition is true;
}else{
some code to be executed if condition is false;
}
If ..else.. statement flowchart:
Example:
<?php
$age = 10;
if ($age < 20) {
echo " Welcome ! this condition is true ";
}else{
echo " Welcome ! this condition is false ";
}
?>
The PHP If ..else if..else statement
The if statement executes some code if one is true. if condition is false then second condition is true if condition is false then execute else part code
Syntax:
if (condition) {
some code to be executed if condition is true;
}else if (condition) {
some code to be executed second if condition is true;
}else{
some code to be executed when first and second condition is false;
}
If ..else if.. else statement flowchart:
Example:
<?php
$age = 10;
if ($age < 20) {
echo " Welcome ! this condition is true ";
}else if ($age < 20) {
echo " Welcome ! first condition is false and second condition is true ";
}else{
echo " Welcome ! fisrt and second condition is false ";
}
?>