- PHP Loops (while, do while, foreach & for) Tutorial
- PHP Flow Control and Looping
- Contents
- PHP Conditional Statements
- The PHP if Statement
- The PHP if . else Statements
- PHP Looping Statements
- PHP for loops
- PHP while loops
- PHP do . while loops
- PHP switch Statements
- Breaking a Loop
- Breaking Out of Nested Loops
- Skipping Statements in Current Loop Iteration
PHP Loops (while, do while, foreach & for) Tutorial
In this tutorial, we learn how to control the flow of our application even further. We learn how PHP can help us iterate through sections of code with while, do-while, for and foreach loop statements.
We also cover so called nested loops, which are loops inside other loops. And finally, we compare each loop and explain when to use which one.
By default, the flow of an application written in PHP is sequential. It starts at the top and flows sequentially to the bottom. Many times we will need to alter this flow and allow specific sections of code to be repeated multiple times.
For this purpose, PHP offers us various types of iteration, or looping, logic which are capable of repeating sections of code. Iteration helps us with repetitive tasks and when dealing with big data.
As an example, let’s consider a database for a mailing list which contains entries for a name and email address.
When we want to send an email to everyone on the list, we will need to iterate through all the users in the database one by one. We then fetch their email address and send them an email.
The interpreter will start at the first user and send an email to that user. If there are more users in the database, it will process the next user in the database and send them an email too.
This process loops over and over for all the users in the database, or until we tell it to stop.
PHP offers us four types of loop statements:
A while loop will tell the interpreter to execute its code block repeatedly, as long as the while expression remains true. The expression will be evaluated each time at the beginning of the loop’s iteration.
The basic form of a while loop is as follows.
PHP Flow Control and Looping
One of the main reasons for using scripting languages such as PHP is to build logic and intelligence into the creation and deployment of web based data. In order to be able to build logic into PHP based scripts, it is necessary for the script to be able to make decisions and repeat tasks based on specified criteria.
For example, it may be necessary to repeat a section of a script a specified number of times, or perform a task only if one or more conditions are found to be true (i.e. only let the user log in if a valid password has been provided).
In programming terms this is known as flow control and looping. In the simplest terms this involves some standard scripting structures provided by languages such as PHP to control the logic and overall behavior of a script. Each of these structures provides a simple and intuitive way to build intelligence into scripts. These PHP structures can be broken down into a number of categories as follows:
In this chapter we will explore each of these categories in turn and create some examples that demonstrate how to implement these mechanisms.
Contents
PHP Conditional Statements
Just about everything in life revolves around decisions. We wouldn’t get very far through the day if we weren’t able to decide what to wear, what to eat and which roads to traverse on the way to work. Similarly computers would be of little use without some innate ability to evaluate choices and make decisions. If all we were able to do was provide a computer with a set of instructions that simply followed one after the other with no ability to make choices based on specific criteria, none of the software we have today would exist.
Conditional statements provide the core of building decision making into scripting languages such as PHP. Conditional statements essentially control whether a part of a script is executed depending the result of a particular expression (i.e. whether an expression returns a boolean true or false value). The two types of conditional structures provided by PHP (and most other programming languages) are if and if . else. In this section we will take a close look at each of these conditional structures, and also provide some examples of their use.
The PHP if Statement
The basic building block of conditional coding is the if statement. The first line of an if statement consists of the if statement followed by the expression to be evaluated in parentheses. For example:
In the above example if the value of the $myVar variable is evaluated to be less than 2 the expression will be evaluated as being true, otherwise it will be evaluated to be false
The second step in constructing an if statement involves specifying the action to be taken when the expression is evaluated to be true. This is achieved by placing the lines of script to be executed in open and closing braces after the if statement:
Note that if there is only one line of script to be performed if the if expression is true then the braces are optional:
Whilst this is perfectly valid PHP it is strongly recommended, for the purposes of consistent scripting style, that the braces be used even for a single line of script after the ‘if’ statement. This makes the script easier to read and avoids a common mistake of later adding new commands that are conditional on the if statement and forgetting to add the braces.
The PHP if . else Statements
The if statement above allows you to specify what should happen if a particular expression evaluates to true. It does not, however, provide the option to specify something else that should happen in the event that the expression evaluates to be false. This is where the if . else construct comes into play.
The syntax for if . else is the same as for the if statement with the exception that the else statement can be used to specify alternate action:
As shown in the above example the script following the if statement is executed when the expression is evaluated to be true (i.e. the $customerName variable contains the string «Simon») and the script after the else statement is executed when the $customerName value does not match the string «Simon».
if . else structures can be taken a step further to implement if . else . if structures. For example:
else if ($customerName == "Graham") < echo 'Hello Graham'; >else < echo 'You are not Simon or Graham.'; >?>
PHP Looping Statements
It is generally accepted that computers are great at performing repetitive tasks an infinite number of times, and doing so very quickly. It is also common knowledge that computers really don’t do anything unless someone programs them to tell them what to do.
Loop statements are the primary mechanism for telling a computer to perform the same task over and over again until a set of criteria are met. This is where for, while and do . while loops are of use.
PHP for loops
Suppose you wanted to add a number to itself ten times. One way to do this might be to write the following PHP script:
Whilst this is somewhat ungainly and time consuming to type, it does work. What would happen, however, if there was a requirement to perform this task 100 times or even 10,000 times. Writing a script to perform this as above would be prohibitively time consuming. This is exactly the situation the for loop is intended to handle.
The syntax of a PHP for loop is as follows:
for ( initializer; conditional expression; loop expression ) < // PHP statements to be executed go here >
The initializer typically initializes a counter variable. Traditionally the variable $i is used for this purpose. For example:
This sets the counter to be the value $i and sets it to zero.
The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of times. For example, if we want to loop 1000 times:
Finally, the loop expression specifies the action to perform on the counter variable. For example to increment by 1:
Bringing this all together we can create a for loop to perform the task outlined in the earlier in this section:
As with the if statement, the enclosing braces are optional if a single line of script is to be executed, but their use is strongly recommended.
PHP while loops
The PHP for loop described previously works well when you know in advance how many times a particular task needs to be repeated in a script. Clearly, there will frequently be instances where code needs to be repeated until a certain condition is met, with no way of knowing in advance how many repetitions are going to be needed to meet that criteria. To address this PHP, provides the while loop.
Essentially, the while loop repeats a set of tasks until a specified condition is met. The while loop syntax is defined follows:
In the above syntax, condition is an expression that will return either true or false and the // PHP statements go here comment represents the PHP to be executed while the expression is true. For example:
In the above example the while expression will evaluate whether $myCount is less than 100. If it is already greater than 100 the code in the braces is skipped and the loop exits without performing any tasks. If $myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of $myCount. This process repeats until $myCount is greater than 100, at which point the loop exits.
PHP do . while loops
You can think of the do . while loop as an inverted while loop. The while loop evaluates an expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check then the code is not executed. The do .. while loop, on the other hand, is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once. For example, you may want to keep stepping through the items in an array until a specific item is found. You know that you have to at least check the first item in the array to have any hope of finding the entry you need. The syntax for the do . while loop is as follows:
while (conditional expression) ?>
In the do . while example below the loop will continue until $i equals 0:
PHP switch Statements
The if . else conditional construct described earlier in this chapter works well if you need to check a value against a few different criteria (for example checking the value of a string against a couple of possible candidates):
else if ($customerName == "Fred") < echo 'Hello Fred!'; >else < echo 'Who are you?'; >?>
This can quickly become cumbersome, however, when a need arises to evaluate a large number of conditions. A much easier way to handle such situations is to use the PHP switch statement, the syntax for which is defined as follows:
There can be any number of case statements — basically as many as you need to fully compare the value in the switch statement against the possible options (represented by match1 through to match5 in the above example) specified by the case statements. When a match is found the PHP statements corresponding to the matching case are executed. Note the break; statement in each case — this is important. Without the break; all the cases after the matching case will also be executed when a match is found.
The default statement specifies the action that should be taken if no match is found. The following provides an example of the switch statement in action:
Breaking a Loop
Occasionally it is necessary to exit from a loop before it has met whatever completion criteria were specified. To achieve this, the break statement must be used. The following example contains a loop that uses the break statement to exit from the loop when i = 100, even though the loop is designed to iterate 1000 times:
Breaking Out of Nested Loops
One problem that can arise using the break statement involves breaking from a loop that is nested inside another loop. In the following example the break will break out of the inner loop, but not the outer loop:
In the above example the break will break out of the inner loop when $x is equal to 10 but the outer for loop will continue to run. This is fine if that is the desired behavior, but is a problem if the outer loop needs to also be broken at this point. This problem can be resolved using the break statement followed by the number of loops you from which you wish to break out. The syntax for this type of break is:
where n represents the number of loop levels from which to break. With this knowledge we can modify our previous example to break out of both loops using a break 2; statement:
Skipping Statements in Current Loop Iteration
The break statement, when encountered in a loop breaks skips all remaining statements in the loop body and breaks the loop. The continue statement also skips all remaining statements in the loop for the current iteration, but returns to the top of the loop and allows it to continue running.