php conditional statement with if else elseif
Posted By
Bajarangi soft ,
Posted On 02-02-2024
if elseif and else statements in PHP. In PHP, the if statement is used to make decisions based on conditions
PHP Conditional Statements
While writing programs/scripts, there will be scenarios where you would want to execute a particular statement only if some condition is satisfied. In such situations we use Conditional statements.
There are several statements in PHP that you can use to make decisions:
- The if statement
- The if...else statement
- The if...else...if statement
- Switch case statement
if Statement
- The if statement allows you to check if a particular condition evaluates to true. If the statement is true, PHP will run the code within the curly brackets (
{}
).
- This is the simplest PHP's conditional statements and can be written like this,
if(condition) {
// your code goes here
}
Example :
<?php
$age = 19;
if ($age > 18) {
echo "You are eligible for voting";
}
?>
Output :
You are eligible for voting
The if...else statement
We use if..else condition when one condition if true and another conditionis false.
if(condition)
{
// true condition
}
else
{
// false condition
}
Example :
<?php
$age = 17;
if ($age > 18) {
echo "You are eligible for voting";
}
else{
echo "Yor are not eligible for voting";
}
?>
Output :
Yor are not eligible for voting
The if...else...if statement
If we have more than two condition then we can use If...else...if statement for check multiple conditions.
if(condition1) {
// if condition1 is true
} elseif(condition2) {
// if the condition1 is false and condition2 is true
} else{
// if both condition1 and condition2 are false
}
Example :
<?php
$age = 19;
if ($age < 18)
{
echo "You are not eligible for voting";
}
elseif ($age>50)
{
echo "over aged person";
}
else
{
echo "Yor are eligible for voting";
}
?>
Output :
Yor are eligible for voting
Switch case statement
- When we have to check multiple condition for one statement then we use switch case statement.
- Default statement is last statement if any case does not match then it will use default case.
- every break statement terminate the statements If break is not used, all the statements will execute after finding matched case value.
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Example :
<?php
$day = 5;
switch($day){
case "1":
echo "Today is Monday.";
break;
case "2":
echo "Today is Tuesday.";
break;
case "3":
echo "Today is Wednesday.";
break;
case "4":
echo "Today is Thursday.";
break;
case "5":
echo "Today is Friday.";
break;
case "6":
echo "Today is Saturday.";
break;
case "7":
echo "Today is Sunday.";
break;
default:
echo "Enter valid day";
break;
}
?>
Output :
Today is Friday.