Menu
Coddy logo textTech

For Loop

Part of the Fundamentals section of Coddy's PHP journey — lesson 47 of 71.

Loops allow you to execute a block of code multiple times without writing it repeatedly. The for loop is ideal when you know exactly how many times you want to repeat something.

A for loop has three parts separated by semicolons: initialization, condition, and increment.

<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . "\n";
}
?>

This outputs the numbers 1 through 5, each on a new line. Here's how it works:

  • $i = 1 — sets the starting value (runs once)
  • $i <= 5 — checks if the loop should continue
  • $i++ — increases $i after each iteration

The loop keeps running as long as the condition is true. Once $i becomes 6, the condition fails and the loop stops.

You can also count backwards or use different step values:

<?php
for ($i = 10; $i >= 0; $i -= 2) {
    echo $i . "\n";
}
?>

This counts down from 10 to 0 by twos: 10, 8, 6, 4, 2, 0.

challenge icon

Challenge

Easy

Read two integers from input: a starting number and an ending number.

Use a for loop to print all numbers from the starting number to the ending number (inclusive), each on a separate line.

Example 1:

If the inputs are 3 and 7, the output should be:

3
4
5
6
7

Example 2:

If the inputs are 1 and 4, the output should be:

1
2
3
4

Cheat sheet

The for loop executes a block of code a specific number of times. It has three parts separated by semicolons: initialization, condition, and increment.

<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . "\n";
}
?>

How it works:

  • $i = 1 — initialization: sets the starting value (runs once)
  • $i <= 5 — condition: checks if the loop should continue
  • $i++ — increment: increases $i after each iteration

The loop continues as long as the condition is true.

You can count backwards or use different step values:

<?php
for ($i = 10; $i >= 0; $i -= 2) {
    echo $i . "\n";
}
?>

Try it yourself

<?php
// Read input
$start = intval(fgets(STDIN));
$end = intval(fgets(STDIN));

// TODO: Write your code below using a for loop to print numbers from start to end

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals