Skip to Content
Learn
Loops
for

A for loop is commonly used to execute a code block a specific number of times.

for (#expression 1; #expression 2; #expression 3) { # code block }

The for loop syntax includes 3 expressions:

  • The first is evaluated only one time before the first iteration.
  • The second is evaluated before each iteration. If it is TRUE, the code block is executed. Otherwise, the loop terminates.
  • The third is evaluated after each iteration. Note that expressions 1 and 2 have semicolons after them.

In our counting to 10 example, the syntax becomes:

for ($count = 1; $count < 11; $count++) { echo "The count is: " . $count . "\n"; }

The first expression is $count = 1, this initializes the $count variable to 1.

At each iteration, the second expression ($count < 11) is evaluated. As long as this is TRUE, the code block executes.

The final expression ($count++) executes after every iteration. In this example, $count is being incremented by 1 each iteration.

After 10 iterations, the value of the $count variable is 11. This makes the second expression FALSE and the loop execution terminates.

Instructions

1.

We’re going to use a for loop to make a countdown. Our goal is to make it count from 10 down to 3 and then say "Ready!", "Set!", "Go!".

Begin by making a for loop that prints the loop variable at each iteration:

  • Use $i for your loop variable.
  • Initialize $i to 10.
  • Continue looping while $i is greater than or equal to zero.
  • Decrement $i on each iteration.
  • Print $i on each iteration followed by a newline.
2.

Use if, elseif and else statements to modify the output slightly:

  • When the loop variable $i is 10 and until its value is down to 3, it should simply print the loop variable followed by a newline.
  • When the loop variable is 2, it should print "Ready!", followed by a newline.
  • When the loop variable is 1, it should print "Set!", followed by a newline.
  • When the loop variable is 0, it should print "Go!".
Folder Icon

Take this course for free

Already have an account?