0% found this document useful (0 votes)
6 views11 pages

M2S2 - S1 - What Is A Control Structure

A control structure in PHP allows for altering the flow of code execution based on conditions, enabling scripts to respond differently to various inputs. Key control structures include 'if', 'else', 'elseif', 'switch', and various loops like 'while', 'do-while', 'for', and 'foreach'. These structures are essential for developing dynamic applications that require conditional logic and repetitive tasks.

Uploaded by

nightfury.000017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

M2S2 - S1 - What Is A Control Structure

A control structure in PHP allows for altering the flow of code execution based on conditions, enabling scripts to respond differently to various inputs. Key control structures include 'if', 'else', 'elseif', 'switch', and various loops like 'while', 'do-while', 'for', and 'foreach'. These structures are essential for developing dynamic applications that require conditional logic and repetitive tasks.

Uploaded by

nightfury.000017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

What is a Control Structure?

In simple terms, a control structure allows you to control the flow of code
execution in your application. Generally, a program is executed sequentially,
line by line, and a control structure allows you to alter that flow, usually
depending on certain conditions.

Control structures are core features of the PHP language that allow your script
to respond differently to different inputs or situations. This could allow your
script to give different responses based on user input, file contents, or some
other data.

The following flowchart explains how a control structure works in PHP.

As you can see in the above diagram, first a condition is checked. If the
condition is true, the conditional code will be executed. The important thing to
note here is that code execution continues normally after conditional code
execution.

Let's consider the following example.


In the above example, the program checks whether or not the user is logged
in. Based on the user's login status, they will be redirected to either
the Login page or the My Account page. In this case, a control structure
ends code execution by redirecting users to a different page. This is a crucial
ability of the PHP language.

PHP supports a number of different control structures:

• if
• else
• elseif
• switch
• while
• do - while
• for
• foreach
• and more

Let's take a look at a few of these control structures with examples.


Go Through the Different Control Structures

In the previous section, we learned the basics of control structures in PHP and
their usefulness in application development. In this section, we'll go through a
couple of important control structures that you'll end up using frequently in
your day-to-day application development.

If

The if construct allows you to execute a piece of code if the expression


provided along with it evaluates to true.

Let's have a look at the following example to understand how it actually works.

1 <?php
2 $age = 50;
3
4 if ($age > 30)
5 {
6 echo "Your age is greater than 30!";
}
7 ?>
8
The above example should output the Your age is greater than
30! message since the expression evaluates to true. In fact, if you want to
execute only a single statement, the above example can be rewritten as
shown in the following snippet without brackets.

1 <?php
2 $age = 50;
3
4 if ($age > 30)
5 echo "Your age is greater than 30!";
?>
6
On the other hand, if you have more than one statements to execute, you
must use brackets, as shown in the following snippet.

1 <?php
if (is_array($user))
2 {
3 $user_id = isset($user['user_id']) ? $user['user_id'] : '';
4 $username = isset($user['username']) ? $user['username'] : '';
5 // and more statements...
}
6 ?>
7
8

Else

In the previous section, we discussed the if construct, which allows you to


execute a piece of code if the expression evaluates to true. On the other
hand, if the expression evaluates to false, it won't do anything. More often
than not, you also want to execute a different code snippet if the expression
evaluates to false. That's where the else statement comes into the picture.

You always use the else statement in conjunction with an if statement.


Basically, you can define it as shown in the following pseudo code.

1
if (expression)
2 {
3 // code is executed if the expression evaluates to TRUE
4 }
5 else
{
6 // code is executed if the expression evaluates to FALSE
7 }
8
Let's revise the previous example to understand how it works.

01
02 <?php
$age = 50;
03
04 if ($age < 30)
05 {
06 echo "Your age is less than 30!";
07 }
08 else
{
09 echo "Your age is greater than or equal 30!";
10 }
11 ?>
12
So when you have two choices, and one of them must be executed, you can
use the if-else construct.
Else If

We can consider the elseif statement as an extension to the if-


else construct. If you've got more than two choices to choose from, you can
use the elseif statement.

Let's study the basic structure of the elseif statement, as shown in the
following pseudo code.

01
02 if (expression1)
{
03
// code is executed if the expression1 evaluates to TRUE
04 }
05 elseif (expression2)
06 {
07 // code is executed if the expression2 evaluates to TRUE
}
08 elseif (expression3)
09 {
10 // code is executed if the expression3 evaluates to TRUE
11 }
12 else
{
13 // code is executed if the expression1, expression2 and expression3 evaluates to FAL
14 choice
15 }
16
Again, let's try to understand it using a real-world example.

01 <?php
02 $age = 50;
03
if ($age < 30)
04 {
05 echo "Your age is less than 30!";
06 }
07 elseif ($age > 30 && $age < 40)
08 {
echo "Your age is between 30 and 40!";
09 }
10 elseif ($age > 40 && $age < 50)
11 {
12 echo "Your age is between 40 and 50!";
}
13 else
14 {
15 echo "Your age is greater than 50!";
16 }
17 ?>
18
19
20
As you can see in the above example, we have multiple conditions, so we've
used a series of elseif statements. In the event that all if conditions
evaluate to false, it executes the code provided in the last else statement.

Switch

The switch statement is somewhat similar to the elseif statement which


we've just discussed in the previous section. The only difference is the
expression which is being checked.

In the case of the elseif statement, you have a set of different conditions,
and an appropriate action will be executed based on a condition. On the other
hand, if you want to compare a variable with different values, you can use
the switch statement.

As usual, an example is the best way to understand the switch statement.

01 <?php
02 $favourite_site = 'Code';
03
04 switch ($favourite_site) {
05 case 'Business':
echo "My favourite site is business.tutsplus.com!";
06 break;
07 case 'Code':
08 echo "My favourite site is code.tutsplus.com!";
09 break;
10 case 'Web Design':
echo "My favourite site is webdesign.tutsplus.com!";
11 break;
12 case 'Music':
13 echo "My favourite site is music.tutsplus.com!";
14 break;
case 'Photography':
15 echo "My favourite site is photography.tutsplus.com!";
16 break;
17 default:
18 echo "I like everything at tutsplus.com!";
19 }
?>
20
21
22
23
As you can see in the above example, we want to check the value of
the $favourite_site variable, and based on the value of
the $favourite_site variable we want to print a message.

For each value you want to check with the $favourite_site variable, you
have to define the case block. If the value is matched with a case, the code
associated with that case block will be executed. After that, you need to use
the break statement to end code execution. If you don't use
the break statement, script execution will be continued up to the last block in
the switch statement.

Finally, if you want to execute a piece of code if the variable's value doesn't
match any case, you can define it under the default block. Of course, it's not
mandatory—it's just a way to provide a default case.

So that's the story of conditional control structures. We'll discuss loops in PHP
in the next section.

Loops

Loops in PHP are useful when you want to execute a piece of code repeatedly
until a condition evaluates to false. So code is executed repeatedly as long as
a condition evaluates to true, and as soon as the condition evaluates to false,
the script continues executing the code after the loop.

The following flowchart explains how loops work in PHP.


As you can see in the above screenshot, a loop contains a condition. If the
condition evaluates to true, the conditional code is executed. After execution
of the conditional code, control goes back to the loop condition, and the flow
continues until the condition evaluates to false.

In this section, we'll go through the different types of loops supported in PHP.

While Loop

The while loop is used when you want to execute a piece of code repeatedly
until the while condition evaluates to false.

You can define it as shown in the following pseudo code.

1 while (expression)
2 {
3 // code to execute as long as expression evaluates to TRUE
}
4
Let's have a look at a real-world example to understand how the while loop
works in PHP.
01
02 <?php
03 $max = 0;
04 echo $i = 0;
05 echo ",";
echo $j = 1;
06 echo ",";
07 $result=0;
08
09 while ($max < 10 )
10 {
11 $result = $i + $j;
12
$i = $j;
13 $j = $result;
14
15 $max = $max + 1;
16 echo $result;
17 echo ",";
}
18
?>
19
20
If you're familiar with the Fibonacci series, you might recognize what the
above program does—it outputs the Fibonacci series for the first ten numbers.
The while loop is generally used when you don't know the number of
iterations that are going to take place in a loop.

Do-While Loop

The do-while loop is very similar to the while loop, with the only difference
being that the while condition is checked at the end of the first iteration. Thus,
we can guarantee that the loop code is executed at least once, irrespective of
the result of the while expression.

Let's have a look at the syntax of the do-while loop.

1 do
2 {
3 // code to execute
} while (expression);
4
Let's go through a real-world to understand possible use-cases where you can
use the do-while loop.

01 <?php
02 $handle = fopen("file.txt", "r");
if ($handle)
03 {
04 do
05 {
06 $line = fgets($handle);
07
08 // process the line content
09
} while($line !== false);
10 }
11 fclose($handle);
12 ?>
13
14
In the above example, we're trying to read a file line by line. Firstly, we've
opened a file for reading. In our case, we're not sure if the file contains any
content at all. Thus, we need to execute the fgets function at least once to
check if a file contains any content. So we can use the do-while loop
here. do-while evaluates the condition after the first iteration of the loop.

For Loop

Generally, the for loop is used to execute a piece of code for a specific
number of times. In other words, if you already know the number of times you
want to execute a block of code, it's the for loop which is the best choice.

Let's have a look at the syntax of the for loop.

1 for (expr1; expr2; expr3)


2 {
3 // code to execute
}
4
The expr1 expression is used to initialize variables, and it's always executed.
The expr2 expression is also executed in the beginning of a loop, and if it
evaluates to true, the loop code is executed. After execution of the loop code,
the expr3 is executed. Generally, the expr3 is used to alter the value of a
variable which is used in the expr2 expression.

Let's go through the following example to see how it works.


1 <?php
2 for ($i=1; $i<=10; ++$i)
3 {
4 echo sprintf("The square of %d is %d.</br>", $i, $i*$i);
}
5 ?>
6
The above program outputs the square of the first ten numbers. It
initializes $i to 1, repeats as long as $i is less than or equal to 10, and adds
1 to $i at each iteration.

For Each

The foreach loop is used to iterate over array variables. If you have an array
variable, and you want to go through each element of that array,
the foreach loop is the best choice.

Let's have a look at a couple of examples.

01
02 <?php
03 $fruits = array('apple', 'banana', 'orange', 'grapes');
04 foreach ($fruits as $fruit)
{
05 echo $fruit;
06 echo "<br/>";
07 }
08
09 $employee = array('name' => 'John Smith', 'age' => 30, 'profession' => 'Software Enginee
foreach ($employee as $key => $value)
10 {
11 echo sprintf("%s: %s</br>", $key, $value);
12 echo "<br/>";
13 }
14 ?>
15
If you want to access array values, you can use the first version of
the foreach loop as shown in the above example. On the other hand, if you
want to access both a key and a value, you can do it as shown in
the $employee example above.

You might also like