Menu
Coddy logo textTech

While Loop

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

While the for loop works great when you know the exact number of iterations, the while loop is perfect when you want to keep looping until a condition becomes false.

A while loop checks its condition before each iteration. If the condition is true, the code inside runs. This continues until the condition becomes false.

<?php
$count = 1;

while ($count <= 3) {
    echo "Count: $count\n";
    $count++;
}
?>

This outputs:

Count: 1
Count: 2
Count: 3

The loop starts by checking if $count <= 3. Since it's true, the code runs and increments $count. When $count reaches 4, the condition fails and the loop stops.

Important: Always ensure something inside the loop eventually makes the condition false. Otherwise, you'll create an infinite loop that never stops running.

<?php
$total = 0;
$num = 1;

while ($total < 10) {
    $total += $num;
    $num++;
}

echo $total;
?>

This keeps adding numbers until the total reaches or exceeds 10, then outputs the final value.

challenge icon

Challenge

Easy

Read a single integer from input representing a target sum.

Use a while loop to add consecutive numbers starting from 1 (1, 2, 3, 4, ...) until the total reaches or exceeds the target sum.

Print the final total on the first line, and the last number that was added on the second line.

Example 1:

If the input is 10, the output should be:

10
4

(1 + 2 + 3 + 4 = 10, which reaches the target)

Example 2:

If the input is 15, the output should be:

15
5

(1 + 2 + 3 + 4 + 5 = 15)

Example 3:

If the input is 7, the output should be:

10
4

(1 + 2 + 3 + 4 = 10, which exceeds 7)

Cheat sheet

A while loop checks a condition before each iteration and continues running until the condition becomes false.

Basic syntax:

<?php
$count = 1;

while ($count <= 3) {
    echo "Count: $count\n";
    $count++;
}
?>

The loop checks if $count <= 3 before each iteration. When the condition becomes false, the loop stops.

Important: Always ensure something inside the loop eventually makes the condition false to avoid infinite loops.

Example with accumulation:

<?php
$total = 0;
$num = 1;

while ($total < 10) {
    $total += $num;
    $num++;
}

echo $total;
?>

Try it yourself

<?php
// Read the target sum
$target = intval(fgets(STDIN));

// Initialize variables
$total = 0;
$num = 0;

// TODO: Write your code here
// Use a while loop to add consecutive numbers (1, 2, 3, ...)
// until the total reaches or exceeds the target


// Output the final total and the last number added
echo $total . "\n";
echo $num;
?>
quiz iconTest yourself

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

All lessons in Fundamentals