In this tutorial, you shall learn about If conditional statement in PHP, its syntax, how to write an If conditional statement in PHP programs, and how to use it, with the help of a few example scenarios.

PHP If

PHP If statement is a conditional statement that can conditionally execute a block of statements based on the result of an expression.

Syntax

The syntax of PHP If statement is

</>
Copy
if (condition) {
  // if-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.

If the condition evaluates to true, PHP executes if-block statement(s). If the condition is false, PHP does not execute if-block statement(s). After any of the two possible scenarios, PHP execution continues with the subsequent PHP statements.

Example

The following is a simple PHP program to demonstrate the working of If 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 ?. if-block statement(s) is only a single echo statement.

PHP Program

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

Output