Browse free website templates that organized by category.
This text and video tutorial covers PHP flow control including if, elseif and else 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.
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 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 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'; } ?>