PHP Conditional Statements Tutorial

This text and video tutorial covers PHP flow control including if, elseif and else statements.

What Are Conditional Statements

In PHP, conditional statements are used to have PHP scripts execute a set of pre-determined actions if a given condition (or conditions) is true and another set of pre-determined actions if a given condition (or conditions) is false. There are two conditional structures in PHP: if, elseif and else statements and switch statements.

The list below gives you a brief description of each conditional statement.

  • if statement - this conditional statement executes a set of instructions only if a specified condition is true
  • if...else statement - this conditional statement executes a set of code if a condition (or conditions) is true and another set of instructions if the condition is false
  • if elseif else statement - this conditional statement executes one of several sets of instructions depending on whether one (or more) set of conditions is true or false
  • switch statement - this conditional statement is similar to a series of if elseif and else statements. Switch statements should be used when there are more than a few set of conditions which can be true or false

if Statements

This condition is used to execute one set of instructions only if one condition (or set of conditions) is true

The syntax of an if statement is shown below.

if (condition){ code to be executed if condition is true; }

The code below is an example of an if statement.

<?php $password = 'password'; if ($password == 'password'){ echo 'The password is correct.'; } ?>

The PHP code would output the text "Today is Monday", since the condition is true.

if else Statements

if...else statements execute a set of code if a condition (or conditions) is true and another set of instructions if the condition is false

The syntax of an if else statement is shown below.

if (condition){ code to be executed if condition is true; } else { code to be executed if condition is false; }

The code below is an example of an if else statement.

<?php $name = 'Mike'; if ($name == 'John'){ echo 'Hello John'; } else { echo 'You are not John'; } ?>

The PHP code would output the text "False", since the condition is false.

if elseif else Statements

if elseif else statements execute one of several sets of instructions depending on whether one (or more) set of conditions is true or false.

The syntax of an if elseif else statement is shown below.

if (condition){ code to be executed if condition is true; } elseif (condition){ code to be executed if condition is true; } else { code to be executed if condition is false; }

The code below is an example of an if elseif else statement.

<?php $name = 'boss'; if ($name == 'boss'){ echo 'Hi boss'; } elseif ($name == 'James'){ echo 'Hi James'; } else { echo 'Hi'; } ?>