PHP: For Loops II

Derek Bridge

Department of Computer Science,
University College Cork

PHP: For Loops II

Aims:

The for-loop

Flowchart

[A flowchart showing a general for-loop.]

Some observations

Common error

Off-by-one errors

Class exercise

Assuming $m and $n contain non-negative integers and that $n >= $m, how many iterations will there be of the following loops?

  1. for ( $i = $m; $i < $n; $i++ )
    {
        echo "<p>{$i}</p>";
    }
  2. for ( $i = $m; $i <= $n; $i++ )
    {
        echo "<p>{$i}</p>";
    }

More general for-loops

Example

$current_year = (int) date('Y');
for ( $year = 1948; $year <= $current_year; $year += 4 )
{
    echo "<p>{$year} was an Olympic year</p>";
}

Class exercise

The version below is also correct but the previous version is better than this version. Why?

for ( $year = 1948; $year <= (int) date('Y'); $year += 4 )
{
    echo "<p>{$year} was an Olympic year</p>";
}

Class exercises

  1. Write a for-loop that echoes the numbers from 36 to 1 (inclusive) in that order
  2. Write a for-loop that never terminates (an infinite loop), forever printing consecutive integers starting from 0
  3. Rewrite the following so that as much code as possible is moved into the for-loop header
    $number = (int) $_GET['number'];
    
    $total = 0;
    for ( $i = 1; $i <= $number; $i++ )
    {
        $total += $i;
    }
    echo "<p>The sum of the numbers from 1 to {$number} is {$total}</p>";

Advice