PHP if.. else Statement

In this chapter, we’ll look at how to use PHP if.. else Statement to build decision-making code.

PHP Conditional Statements:

Conditional statements are used to do various actions in response to various conditions.

When writing code, it’s common to take multiple actions depending on the situation. To accomplish this, you can utilize conditional statements in your code.

Following are conditional statements in PHP:

  • If statement
  • if else statement
  • if.. elseIf… else statement
  • switch statement

PHP – if Statement

The if statement is used to run a set of instructions only If the given condition is true.

Syntax:
if(condition)
{
// code to be executed
}
<h2>IF statement Example</h2>
<?php
$t = date("D");

if ($t == "Fri") {
  echo "Have a good weekend!";// Output is not shown if its not Friday as there is no else condition.
}
?>

PHP if.. else Statement

PHP if.. else statement is used to run some piece of code If the given condition is true, else it runs other piece of code if the given condition is false.

By adding an else statement to the if statement, you can improve the decision-making process by giving the user another option.

Syntax:
if(condition)
{
// code to be executed if condition is true
}
else
{
// code to be executed if condition is false
}
<h2>IF.. else statement Example</h2>
<?php
$t = date("D");

if ($t == "Fri") {
  echo "Have a good weekend!";
}
else {
	echo "Have a good Day!";
    }
?>

PHP -if…elseif…else Statement

If you want to combine many if…else statements, you can use the if…elseif…else Statement. So basically, it is used for multiple conditions.

Syntax:
if(condition1)
{
     // code to be executed if condition1 is true
}

elseif(condition2)
{
    // code to be executed if condition2 is true
}

else
{
    // code to be executed if both conditions are false
}
<h2>IF.. elseif.. else statement Example</h2>
<?php
$t = date("D");

if ($t == "Fri") {
  echo "Have a good weekend!";
}
else if($t=="Sun"){
	echo "Have a good Sunday!";
    }
else {
	echo "Have a good Day!";
    }
?>