Jump to content

PHP Programming/The for Loop

From Wikibooks, open books for an open world

The for loop

[edit | edit source]

The for loop is one of the basic looping structures in most modern programming languages. Like the while loop, for loops execute a given code block until a certain condition is met.

Syntax

[edit | edit source]

The basic syntax of the for loop in PHP is similar to the C syntax:

 for ([initialization]; [condition]; [step])

Initialization happens the first time the loop is run. It is used to initialize variables or perform other actions that are to be performed before the first execution of the body of the loop.

The condition is evaluated before each execution of the body of the loop; if the condition is true, the body of the loop will be executed, if it is false, the loop is exited and program execution resumes at the first line after the body of the loop.

Step specifies an action that is to be performed after each execution of the loop body.

Consider this example:

PHP Code:

for ($i = 0; $i < 5; $i++) {
  echo($i . "&lt;br /&gt;");
}

PHP Output:

0<br />1<br />2<br />3<br />4<br />

HTML Render:

 0
 1
 2
 3
 4


The loop can also be formatted without using concatenation, according to personal preference:

for ($i = 0; $i < 5; $i++) {
  echo "$i&lt;br /&gt;";
}

Explanation

[edit | edit source]

Within the for loop, it is indicated that $i starts as 0. When the loop runs for the first time, it prints the initial value of $i, which in the case of the example is 0. For every loop, the variable $i is increased by one (denoted by the $i++ incrementing step). When $i reaches 5 it is no longer less than 5 and therefore the loop stops.

Do note that the initialisation, condition and step for the for-loop can be left empty. In this case, the loop will continue indefinitely and subsequently a break execution can be utilised to stop the loop.

NOTE: In contrast to other languages like C, C#, C++, or Java, the variable used in the for loop may have been initialised first in the line with the for statement, but it continues to exist after the loop has finished.

Using for loops to traverse arrays

[edit | edit source]

In the section on while loops, the sort() example uses a while loop to print out the contents of the array. Generally programmers use for loops for this kind of job.

Example

[edit | edit source]

NOTE: Use of indices like below is highly discouraged. Use the key-value for-loop construct.

$menu = array("Toast and jam", "Bacon and eggs", "Homefries", "Skillet", "Milk and cereal");
// Note to self: get breakfast after writing this article
$count = count($menu);
for ($i = 0; $i < $count; $i++) {
  echo ($i + 1 . ". " . $menu[$i] . "&lt;br /&gt;");
}

Again, this can be formatted without concatenation, if you prefer:

for ($i = 0; $i < $count; $i++) {
  $j = $i + 1;
  echo "$j. {$menu[$i]}&lt;br /&gt;";
}

Explanation

[edit | edit source]
$count = count($menu);

We define the count before the for loop for more efficient processing. This is because each time the for loop is run (while $i < $count) it evaluates both sides of the equation and executes any functions. If we put $i < count($menu), this would evaluate count($menu) each time the process is executed, which is costly when dealing with large arrays.

for ($i = 0; $i < $count; $i++)

This line sets up the loop. It initializes the counter, $i, to 0 at the start, adds one every time the loop goes through, and checks that $i is less than the size of the array.

This can also be done using a second initialization.

for ($i = 0, $count = count($menu); $i < $count; $i++) {
  echo ($i + 1 . ". " . $menu[$i] . "&lt;br /&gt;");
}

The echo statement is pretty self-explanatory, except perhaps the bit at the start, where we echo $i + 1. We do that because, as you may recall, arrays start at 0 and end at n - 1 (where n is their length), so to get a numbered list starting at one, we have to add one to the counter each time we print it.

Of course, as I mentioned before, both pieces of code produce the following output:

  1. Toast and jam ✓
  2. Bacon and eggs ✓
  3. Homefries ✓
  4. Skillet ✓
  5. Milk and cereal ✓

Believe it or not, there's actually a way to traverse arrays that requires even less typing. (And isn't that the goal?) Check out the foreach loop for another way of doing what we did here.

For more information

[edit | edit source]