Menu
CoddyTech

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

The lines above your code already read the target sum into $target and set $total and $num to 0, so do not read the input again.

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

The lines below your code print the final total and the last number that was added.

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)

Try it yourself

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


quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online PHP compiler