PHP - Decision Making in Control Statement or Control Flow
PHP - Decision Making in Control Statement or Control Flow
PHP allows us to perform actions based on some type of conditions that may be logical or comparative.
Based on the result of these conditions i.e., either TRUE or FALSE, an action would be performed as asked
by the user. It’s just like a two- way path. If you want something then go this way or else turn that way. To
use this feature, PHP provides us with four conditional statements:
if statement
if…else statement
if…elseif…else statement
switch statement
if statement
The if statement allows you to execute a statement if an expression evaluates to true.
PHP evaluates the expression first. If the expression evaluates to true, PHP executes the statement. In case
the expression evaluates to false, PHP ignores the statement.
Syntax:
if ( expression )
statement;
Flowchart
Example: uses the if statement to display a message if the $is_admin variable sets to true:
File: .php
Input:
<?php
$is_admin = true;
if ($is_admin)
echo 'Welcome, admin!';
?>
Output:
Welcome, admin!
Curly braces
If you want to execute multiple statements in the if block, you can use curly braces to group multiple
statements
Syntax:
if ( expression ) {
statement1;
statement2;
// more statement
}
Input:
<?php
$can_edit = false;
$is_admin = true;
if ( $is_admin ) {
echo 'Welcome, admin!';
$can_edit = true;
}
?>
Output:
In this example, the if statement displays a message and sets the $can_edit variable to true if the
$is_admin variable is true.
It’s a good practice to always use curly braces with the if statement even though it has a single statement
to execute like this:
<?php
if ( expression ) {
statement;
}
In addition, you can use spaces between the expression and curly braces to make the code more readable.
Nesting if statements
It’s possible to nest an if statement inside another if statement as follows:
if ( expression1 ) {
// do something
if( expression2 ) {
// do other things
}
}
Input:
<?php
$is_admin = true;
$can_approve = true;
if ($is_admin) {
echo 'Welcome, admin!';
if ($can_approve) {
echo 'Please approve the pending items';
}
}
Example:
File: .php
Input:
<?php if ( expession) : ?>
<!-- HTML code here -->
<?php endif; ?>
Example: uses the if statement that shows the edit link if the $is_admin is true:
File: .php
Input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP if Statement Demo</title>
</head>
<body>
<?php $is_admin = true; ?>
<?php if ( $is_admin ) : ?>
<a href="#">Edit</a>
<?php endif; ?>
<a href="#">View</a>
</body>
</html>
Since the $is_admin is true, the script shows the Edit link. If you change the value of the $is_admin to false,
you won’t see the Edit link in the output.
Example:
File: .php
Input:
<?php
$checked = 'on';
if( $checked = 'off' ) {
echo 'The checkbox has not been checked';
}
This script shows a message if the $checked is 'off'. However, the expression in the if statement is an
assignment, not a comparison:
$checked = 'off'
This expression assigns the literal string 'off' to the $checked variable and returns that variable. It doesn’t
compare the value of the $checked variable with the 'off' value. Therefore, the expression always evaluates
to true, which is not correct.
To avoid this error, you can place the value first before the comparison operator and the variable after the
comparison operator like this:
Example:
File: .php
Input:
<?php
$checked = 'on';
if('off' == $checked ) {
echo 'The checkbox has not been checked';
}
If you accidentally use the assignment operator (=), PHP will raise a syntax error instead:
Example:
File: .php
Input:
<?php
$checked = 'on';
if ('off' = $checked) {
echo 'The checkbox has not been checked';
}
Error:
PHP if else
Introduction to PHP if-else statement
The if statement allows you to execute one or more statements when an expression is true:
Example:
File: .php
Input:
<?php
if ( expression ) {
// code block
}
Sometimes, you want to execute another code block if the expression is false. To do that, you add the else
clause to the if statement:
Example:
File: .php
Input:
<?php
if ( expression ) {
// code block
} else {
// another code block
}
In this syntax, if the expression is true, PHP executes the code block that follows the if clause. If the
expression is false, PHP executes the code block that follows the else keyword.
The following flowchart illustrates how the PHP if-else statement works:
example uses the if...else statement to show a message based on the value of the $is_authenticated
variable:
Example:
File: .php
Input:
<?php
$is_authenticated = false;
if ( $is_authenticated ) {
echo 'Welcome!';
} else {
echo 'You are not authorized to access this page.'
}
In this example, the $is_authenticated is false. Therefore, the script executes the code block that follows
the else clause. And you’ll see the following output:
Input:
<?php if ( expression ): ?>
<!--Show HTML code when expression is true -->
<?php else: ?>
<!--Show HTML code when expression is false -->
<?php endif ?>
Note that you don’t need to place a semicolon (;) after the endif keyword because the endif is the last
statement in the PHP block. The enclosing tag ?> automatically implies a semicolon.
The following example uses the if...else statement to show the logout link if $is_authenticated is true. If
the $is_authenticated is false, the script shows the login link instead:
Example:
File: .php
Input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP if Statement Demo</title>
</head>
<body>
<?php $is_authenticated = true; ?>
<?php if ($is_authenticated) : ?>
<a href="#">Logout</a>
<?php else: ?>
<a href="#">Login</a>
<?php endif ?>
</body>
</html>
PHP if elseif
Introduction to the PHP if elseif statement
The if statement evaluates an expression and executes a code block if the expression is true:
Example:
File: .php
Input:
<?php
if (expression) {
statement;
}
The if statement can have one or more optional elseif clauses. The elseif is a combination of if and else:
Example:
File: .php
Input:
<?php
if (expression1) {
statement;
} elseif (expression2) {
statement;
} elseif (expression3) {
statement;
}
PHP evaluates the expression1 and execute the code block in the if clause if the expression1 is true.
If the expression1 is false, the PHP evaluates the expression2 in the next elseif clause. If the result is true,
then PHP executes the statement in that elseif block. Otherwise, PHP evaluates the expression3.
If the expression3 is true, PHP executes the block that follows the elseif clause. Otherwise, PHP ignores it.
Notice that when an if statement has multiple elseif clauses, the elseif will execute only if the expression in
the preceding if or elseif clause evaluates to false.
The following example uses the if elseif statement to display whether the variable $x is greater than $y:
Example:
File: .php
Input:
<?php
$x = 10;
$y = 20;
if ($x > $y) {
$message = 'x is greater than y';
} elseif ($x < $y) {
$message = 'x is less than y';
} else {
$message = 'x is equal to y';
}
echo $message;
Output:
x is less than y
The script shows the message x is less than y as expected.
Input:
<?php
if (expression):
statement;
elseif (expression2):
statement;
elseif (expression3):
statement;
endif;
In this syntax:
Use a semicolon (:) after each condition following the if or elseif keyword.
Use the endif keyword instead of a curly brace (}) at the end of the if statement.
The following example uses the elseif alternative syntax:
Example:
File: .php
Input:
<?php
$x = 10;
$y = 20;
if ($x > $y) :
$message = 'x is greater than y';
elseif ($x < $y):
$message = 'x is less than y';
else:
$message = 'x is equal to y';
endif;
echo $message;
Input:
<<?php
if (expression) {
statement;
} else if (expression2) {
statement2;
}
Code language: PHP (php)
The else if in this case, is the same as the following nested if...else structure:
if (expression) {
statement;
} else {
if (expression2) {
statement2;
}
}
If you use the alternative syntax, you need to use the if...elseif statement instead of the if...else if
statement. Otherwise, you’ll get an error.
Input:
<?php
$x = 10;
$y = 20;
PHP switch
Introduction to the PHP switch statement
When the value of a single variable determines the number of different choices, you can use the if...elseif
statement.
Suppose that you’re building a website whose users have many roles like admin, editor, author, and
subscriber.
The following example uses an if elseif statement to display a different message based on the role of the
user:
Example:
File: .php
Input:
<?php
$role = 'subscriber';
$message = '';
echo $message;
Output:
Welcome! Check out some new articles.
When the value of a single variable specifies the number of different choices, it’s much cleaner to use the
switch statement like this:
Example:
File: .php
Input:
<?php
$role = 'admin';
$message = '';
switch ($role) {
case 'admin':
$message = 'Welcome, admin!';
break;
case 'editor':
$message = 'Welcome! You have some pending articles to edit';
break;
case 'author':
$message = 'Welcome! Do you want to publish the draft article?';
break;
case 'subscriber':
$message = 'Welcome! Check out some new articles.';
break;
default:
$message = 'You are not authorized to access this page';
}
echo $message;
The switch statement compares an expression with the value in each case.
If the expression equals a value in a case, e.g., value1, PHP executes the code block in the matching case
until it encounters the first break statement.
If there’s no match and the default is available, PHP executes all statements following the default keyword.
In case the default is not specified, and there’s no match, the control is passed to the statement that
follows the switch statement.
The following example uses the switch statement and combines the cases of 'editor' and 'author':
Example:
File: .php
Input:
<?php
$message = '';
$role = 'author';
switch ($role) {
case 'admin':
$message = 'Welcome, admin!';
break;
case 'editor':
case 'author':
$message = 'Welcome! Do you want to create a new article?';
break;
case 'subscriber':
$message = 'Welcome! Check out some new articles.';
break;
default:
$message = 'You are not authorized to access this page';
}
echo $message;
Output:
Welcome! Do you want to create a new article?
In this example, if the role is editor or author, it’ll show the same message.
Input:
<?php
switch (expression):
case value1:
// code block 1
break;
case value2:
// code block 2
break;
default:
// default code block
break;
endswitch;
The alternative syntax is suitable for mixing with the HTML code.
Input:
<?php
$ch = 'c';
switch ($ch)
{
case 'a':
echo "Choice a";
break;
case 'b':
echo "Choice b";
break;
case 'c':
echo "Choice c";
echo "</br>";
case 'd':
echo "Choice d";
echo "</br>";
default:
echo "case a, b, c, and d is not found";
}
?>
Output:
Choice c
Choice d
case a, b, c, and d is not found
Input:
<?php
$car = "Hyundai";
$model = "Tucson";
switch( $car )
{
case "Honda":
switch( $model )
{
case "Amaze":
echo "Honda Amaze price is 5.93 - 9.79 Lakh.";
break;
case "City":
echo "Honda City price is 9.91 - 14.31 Lakh.";
break;
}
break;
case "Renault":
switch( $model )
{
case "Duster":
echo "Renault Duster price is 9.15 - 14.83 L.";
break;
case "Kwid":
echo "Renault Kwid price is 3.15 - 5.44 L.";
break;
}
break;
case "Hyundai":
switch( $model )
{
case "Creta":
echo "Hyundai Creta price is 11.42 - 18.73 L.";
break;
case "Tucson":
echo "Hyundai Tucson price is 22.39 - 32.07 L.";
break;
case "Xcent":
echo "Hyundai Xcent price is 6.5 - 10.05 L.";
break;
}
break;
}
?>
Output:
Hyundai Tucson price is 22.39 - 32.07 L.