PHP Control Structures are at the core of programming logic. They allow a script to react differently depending on what has already occurred, or based on user input and allow the graceful handling of repetitive tasks.
In PHP, there are two primary types of Control Structures: Conditional Statements and Control Loops. In the last article, you saw some brief examples of Control Structures. This time, we will be taking a closer look at them.
Code execution can be grouped into categories as shown below
- Sequential – this one involves executing all the codes in the order in which they have been written.
- Decision – this one involves making a choice given a number of options. The code executed depends on the value of the condition.
A control structure is a block of code that decides the execution path of a program depending on the value of the set condition.
Let’s now look at some of the control structures that PHP supports.
PHP IF Else
If… then… else is the simplest control structure. It evaluates the conditions using Boolean logic
When to use if… then… else
- You have a block of code that should be executed only if a certain condition is true
- You have two options, and you have to select one.
- If… then… else if… is used when you have to select more than two options and you have to select one or more
Syntax The syntax for if… then… else is;
<?php if (condition is true) { block one else block two } ?>
HERE,
- “if (condition is true)” is the control structure
- “block one” is the code to be executed if the condition is true
- {…else…} is the fallback if the condition is false
- “block two” is the block of code executed if the condition is false
How it works The flow chart shown below illustrates how the if the else control structure works
Let’s see this in action The code below uses “if… then… else” to determine the larger value between two numbers.
<?php $first_number = 7; $second_number = 21; if ($first_number > $second_number){ echo "$first_number is greater than $second_number"; }else{ echo "$second_number is greater than $first_number"; } ?>
Output:
21 is greater than 7
PHP Switch Case
Switch… case is similar to the if then… else control structure.
It only executes a single block of code depending on the value of the condition.
If no condition has been met then the default block of code is executed.
It has the following basic syntax.
<?php switch(condition){ case value: //block of code to be executed break; case value2: //block of code to be executed break; default: //default block code break; } ?>
HERE,
- “switch(…){…}” is the control structure block code
- “case value: case…” are the blocks of code to be executed depending on the value of the condition
- “default:” is the block of code to be executed when no value matches with the condition
How it works
The flow chart shown below illustrates how the switch control structure works
Practical example
The code below uses the switch control structure to display a message depending on the day of the week.
<?php $today = "wednesday"; switch($today){ case "sunday": echo "pray for us sinners."; break; case "wednesday": echo "ladies night, take her out for dinner"; break; case "saturday": echo "take care as you go out tonight."; break; default: echo "have a nice day at work"; break; } ?>
Output:
ladies night, take her out for dinner
Control Loops
Frequently in PHP there are instances where you need to perform repetitive tasks, such as formatting data pulled from a database, sending out emails to a mailing list, or cycling through the contents of an array. Control Loops allow you to perform these tasks almost effortlessly.
While Loops
While Loops are the simplest form of loops:
<?php $x=1;while ($x <=10) { print “$x<br>”; $x++; } ?> |
When you run this snippet, you will see the numbers 1 through 10 printed on your screen. Take a look at the code. In many ways, it’s very similar to an If Statement. First is the while identifier, followed by a condition surrounded by parentheses.
The statements nested within the loop will execute as long as the condition within the parentheses evaluates to true. Since the validity of the condition is checked before the loop is executed, if the condition is false, then the statements within the loop will not be executed at all.
Do…While Loops
Do…While Loops are close cousins of While Loops:
<?php $x=11;do { print “$x<br>”; $x++; } while ($x <=10);?> |
The primary difference in how these work is that the validity of the condition in a Do…While Loop is tested after the loop has itinerated once. This means that in the example above, $x would be printed out one time, and then the execution of the loop would end, because $x is greater than 10.
For Loops
<?php for($x=1; $x<=10; $x++) { print “$x<br>”; } ?> |
The above is an example of a For Loop. For Loops are very similar to While Loops, but more convenient to use in many cases. They are also the most complex loops in PHP, borrowing syntax and function heavily from the C Programming language. This is the final control struture we will be covering in this article.
If you guessed that the above snippet would output the same result as the first example of a while loop, you would be right! Let’s take a closer look at why it works like that. Within the parentheses, For Loops take three expressions separated by semi-colons. The first expression is only executed one time, when the loop initializes. In this case, $x is created and given a value of zero.
The next expression is a condition that is checked each time the loop itinerates. Once the condition is false, the loop will stop executing. Just like a while loop, if the condition is found to be false on the first run, none of the statements within the loop will execute even once.
The final expression will be executed each time the loop itinerates after the nested statements have been parsed. Remember that there is no semi-colon after the final expression.
As you can see, this for loop performs the same function as the earlier While Loop, but far more concisely. Typically, it’s best to use a For Loop in situations where you know how many elements you will be cycling through.
The Foreach Loop
This new loop was introduced in PHP version 4. It’s used exclusively for looping through elements of an array, allowing you to easily print out or perform operations on elements within an array. To keep things from getting too complicated, we will wait to cover this particular loop in detail when arrays are introduced.
Things to Remember:
|
Summary
- Control structures are used to control the execution of the program
- The if-then… else is when you have more than route block of code to execute depending on the value of the condition
- Switch… case is used to when you have a number of block codes, and you only have to execute one of them depending on the value of the set case.