Php if else condition

In PHP, if-else is used for conditional statements. there are 3 types to use if-else condition.

1) if condition:- “if” condition will be executed when “if” statement is true.

Syntax:-


<?php
if(conditional_expression)
{

}
?>

Example:- Suppose, You have $x variable and that has value 100 and now you create the condition.


<?php
$x=100;
if($x>90)
{

 echo 'condition is passed';

}
?>
condition is passed

Try it Yourself

2) if else condition:- “if” condition will be executed when “if” statement is true otherwise false condition will be executed.

Syntax:-


<?php
if(conditional_expression)
{

}else{
}
?>

Example:- Suppose, You have $x variable and that has value 80 and now you create the condition.


<?php
$x=80;
if($x>90)
{

 echo 'condition is passed';

}else{

 echo 'condition is failed';

}
?>
condition is failed

Try it Yourself

3) if elseif condition:- “if” condition will be executed when “if” statement is true otherwise check else if condition.

Syntax:-


<?php
if(conditional_expression1)
{

}elseif(conditional_expression2)
{

}else{

}
?>

Example:- Suppose, You have $x variable and that has value 80 and now you create the condition.


<?php
$x=80;
if($x>90)
{

 echo 'x value is greater than 90';

}elseif($x>70 && $x<90){

 echo 'x value is between 70 to 90';

}else{
echo 'condition does not match';
}
?>
x value is between 70 to 90

Try it Yourself

Php if else condition – Interview Questions

Q 1: What is the if-else statement in PHP?

Ans: It executes code based on a condition.

Q 2: Syntax of if-else?

Ans: if ($a > $b) { } else { }

Q 3: Can we use multiple else-if conditions?

Ans: Yes, using elseif.

Q 4: What happens if the condition is false?

Ans: The else block executes.

Q 5: Can conditions be nested?

Ans: Yes, nested if-else is allowed.

Php if else condition – Objective Questions (MCQs)

Q1. The if statement executes a block when the condition is ______.






Q2. Which keyword is used for multiple conditions?






Q3. The else block executes when the if condition is ______.






Q4. Can if statements be nested in PHP?






Q5. Which operator is used to compare values in if?






Related Php if else condition Topics