In this tutorial, you shall learn about If-Else conditional statement in PHP, its syntax, and how to use an if-else statement in programs with the help of some examples.

PHP If Else

PHP If Else statement is a conditional statement that can execute one of the two blocks of statements based on the result of an expression.

Syntax

The syntax of PHP If-Else statement is

</>
Copy
if (condition) {
  // if-block statement(s)
} else {
  // else-block statement(s)
}

where

  • if is a keyword.
  • condition is a boolean expression.
  • if-block statement(s) are a block of statements. if-block can contain none, one or more PHP statements.
  • else is a keyword.
  • else-block statement(s) are a block of statements. else-block can contain none, one or more PHP statements.

If the condition evaluates to true, PHP executes if-block statement(s). If the condition is false, PHP executes else-block statement(s).

Example

The following is a simple PHP program to demonstrate the working of If-Else conditional statement.

We take two variables and assign values to each of them. Then we use if-statement to check if the two variables are equal.

Here, the condition is a equals b ?.

PHP Program

</>
Copy
<?php
  $a = 4;
  $b = 4;
  if ($a == $b) {
    echo "a and b are equal.";
  } else {
    echo "a and b are not equal.";
  }
?>

Output