PHP if...else...elseif Statements
Conditional statements are used to conduct a variety of activities based on certain criteria.
PHP Conditional Statements
You want to carry out different actions for different scenarios when you create code quite regularly. To do this, you can utilize conditions in your code.
In PHP we have the following conditional statements:
if
statement - executes some code if one condition is true.if...else
statement - If a condition is true, some code is executed; else, another code is executed.if...elseif...else
statement - carries out different codes in response to more than two circumstances.switch
statement - chooses one of several code blocks to be run.
PHP - The IF Statement
The if
statement executes some block of code if a given condition is true.
Syntax :-
if (condition) {
code to be executed if condition is true;
}
Example 1 :- The following program display a message "You are major!" only if the given age value is greater than 18.
18)
{
echo "You are major!";
}
?>
Output :-
Example 2 :- The following program display a message "Welcome admin!" if the given username is equal to "admin".
Output :-
Example 3 :- The following program uses two conditions using and
operator and display a
message if both conditions are ture.
= 10 and $aNumber <=20)
{
echo "The number is between 10 and 20";
}
?>
Output :-
Related Links
PHP - The if...else Statement
The If Else statements execute two different block of codes depending on the condition is true or false.
If a given condition is true, then the IF
block statement will execute.
If a given condition is false, then the ELSE
block statement will execute.
Syntax :-
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example 1 :- Checking a person age is eligible or not to vote.
= 18) {
echo "You are eligible to VOTE!";
}
else {
echo "You are not eligible to VOTE!";
}
?>
Output :-
Example 2 :- Checking username and password for login.
Output :-
Related Links
PHP - The if...elseif...else Statement
For more than two circumstances, the if...elseif...else
expression runs separate programs.
The if...elseif...else
expression is used to execute multiple code blocks depending on the conditions.
Syntax :-
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Note:- You can have multiple elseif statement depends on our need.
Example 1:- Finding a maximum number.
$b and $a > $c)
{
echo "A is big";
}
elseif($b > $a and $b > $c)
{
echo "B is big";
}
else
{
echo "C is big";
}
Output :-
Example 2:- Finding a grade of a student.
= 90)
{
echo "A grade";
}
elseif($ave >=80 $a and $ave < 90)
{
echo "B grade";
}
elseif($ave >=60 $a and $ave < 80)
{
echo "C grade";
}
elseif($ave >=40 $a and $ave < 60)
{
echo "D grade";
}
else
{
echo "No grade";
}
Output :-