4 Loops

Before we get into this section of the text, you need to know how to interrupt the terminal. If a program is running, and you want to exit it, press Ctrl+C, just like you were copying some text. It is possible to write programs that never end. The next code sample is one such program. Save the following code into a file and run it. You’ll need to interrupt the program, otherwise it’ll execute forever! Press Ctrl+C once you’ve had enough.

<?php

while(true) {
    print("A");
}

While-loops have a close relative, the for-loop. The while-loop is very similar to an if-statement. It executes the code in the curly braces when the condition in the parentheses is true. The key difference between an if-statement and a while-loop is that when the program reaches the closing curly brace “}” of a while-loop, it hops back to the top and checks the condition again. This can repeat indefinitely as the prior example demonstrated.

A for-loop looks like this:

for($i = 0; i < $max_value; $i++) {
    // do stuff
}

This text will begin omitting “<?php” unless it’s a full file’s contents that is being displayed.

Let’s break the for-loop down. In the parentheses, we declare and initialize a variable, then comes a conditional, and the last part is a piece of code that gets run with every loop. In the last part, we are simply incrementing and storing the value, so “$i = $i + 1” would have the same effect as “$++” here. If the conditional part evaluates to false, the for-loop stops.

Sometimes, a certain task feels like a job for a for-loop, and other tasks feel like they’d be best implemented with a while-loop.

Just like if-statements, loops can be nested. Here’s an example of a nested for-loop that will print a rectangle of asterisks with the dimensions held in the variables $width and $height:

$width = 10;
$height = 10;

for($i = 0; $i < $height; $i++) {
    for($j = 0; $j < $width; $j++) {
        print("*");
    }
    print("\n");
}

Exercises:

  1. Modify the fizzbuzz program from the last chapter to use a loop. Have it run from 1 until a maximum value you can set by editing the value of a variable.

  2. Use a nested for-loop to print a multiplication table. Try to format it well. Note the symmetry of it. Since 4*8 is equal to 8*4, are we making the computer do more work than it needs to?

  3. Can you modify the code that prints a rectangle full of asterisks so that it prints a box instead? With $height = 4 and $width = 5, your code should output:

*****
*   *
*   *
*****