0% found this document useful (0 votes)
7 views

PHP - Decision Making in Control Statement or Control Flow

The document provides an overview of decision-making and control statements in PHP, focusing on conditional statements such as if, if-else, if-elseif-else, and switch. It explains the syntax and usage of these statements, including nesting and embedding within HTML, along with common mistakes and best practices. Additionally, it covers alternative syntaxes and the fall-through behavior of switch statements.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PHP - Decision Making in Control Statement or Control Flow

The document provides an overview of decision-making and control statements in PHP, focusing on conditional statements such as if, if-else, if-elseif-else, and switch. It explains the syntax and usage of these statements, including nesting and embedding within HTML, along with common mistakes and best practices. Additionally, it covers alternative syntaxes and the fall-through behavior of switch statements.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

PHP - Decision Making/Control Statement

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
}

Example : uses the if statement that executes multiple statements:


File: .php

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
}
}

Example: shows how to nest an if statement in another if statement:


File: .php

Input:
<?php
$is_admin = true;
$can_approve = true;
if ($is_admin) {
echo 'Welcome, admin!';
if ($can_approve) {
echo 'Please approve the pending items';
}
}

Embed if statement in HTML


To embed an if statement in an HTML document, you can use the above syntax. However, PHP provides a
better syntax that allows you to mix the if statement with HTML nicely:

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.

A common mistake with the PHP if statement


A common mistake that you may have is to use the wrong operator in the if statement. For example:

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:

Parse error: syntax error, unexpected '=' ...

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:

You are not authorized to access this page.

PHP if…else statement in HTML


Like the if statement, you can mix the if...else statement with HTML nicely using the alternative syntax:
Example:
File: .php

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 flowchart illustrates how the if elseif statement works:

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.

PHP if elseif alternative syntax


PHP also supports an alternative syntax for the elseif without using curly braces like the following:
Example:
File: .php

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;

The alternative syntax is suitable for use with HTML.

PHP elseif vs. else if


PHP allows you to write else if (in two words) that has the same result as elseif (in a single word):
Example:
File: .php

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.

The following example doesn’t work and cause an error:


Example:
File: .php

Input:
<?php
$x = 10;
$y = 20;

if ($x > $y) :


echo 'x is greater than y';
else if ($x < $y):
echo 'x is equal to y';
else:
echo 'x is less than y';
endif;

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 = '';

if ('admin' === $role) {


$message = 'Welcome, admin!';
} elseif ('editor' === $role) {
$message = 'Welcome! You have some pending articles to edit';
} elseif ('author' === $role) {
$message = 'Welcome! Do you want to publish the draft article?';
} elseif ('subscriber' === $role) {
$message = 'Welcome! Check out some new articles.';
} else {
$message = 'Sorry! You are not authorized to access this page';
}

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 following illustrates the syntax of the switch statement:


<?php
switch (expression) {
case value1:
// code block 1
break;
case value2:
// code block 2
break;
case value3:
// code block 3
break;
default:
// default code block
}

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.

Important points to be noticed about switch case:


 The default is an optional statement. Even it is not important, that default must always be the last
statement.
 There can be only one default in a switch statement. More than one default may lead to a Fatal
error.
 Each case can have a break statement, which is used to terminate the sequence of statement.
 The break statement is optional to use in switch. If break is not used, all the statements will execute
after finding matched case value.
 PHP allows you to use number, character, string, as well as functions in switch expression.
 Nesting of switch statements is allowed, but it makes the program more complex and less readable.
 You can use semicolon (;) instead of colon (:). It will not generate any error.

The following flowchart illustrates how the switch statement works:


PHP switch
Combining cases
Since PHP executes the switch statement from the matching case label till it encounters the break
statement, you can combine several cases in one.

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.

PHP switch statement’s alternative syntax


PHP also supports the alternative syntax for the switch statement as follows:
Example:
File: .php

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.

PHP switch statement is fall-through


PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if
break statement is not found.
Example:
File: .php

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

PHP nested switch statement


Nested switch statement means switch statement inside another switch statement. Sometimes it leads to
confusion.
Example:
File: .php

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.

You might also like