All posts
PHPSeptember 26, 20267 min read

PHP Loops for Beginners: For, While & Foreach

PHP loops for beginners explained simply: learn for, while, do-while, and foreach with copy-paste examples and line-by-line breakdowns.

F
Fepiq Team
Fepiq

If you have ever needed to repeat the same action many times in your code, you need a loop. This guide answers the question "how do PHP loops work for beginners?" in plain English. A loop is simply a block of code that runs over and over until a condition tells it to stop. By the end of this article you will understand PHP's four main loop types: for, while, do-while, and foreach, and you will know exactly when to use each one.

What Is a Loop in PHP?

Imagine you want to print the numbers 1 through 5. Without a loop, you would write five separate echo statements. With a loop, you write the instruction once and tell PHP how many times to repeat it. This saves you from copying and pasting code, and it lets your program handle data of any size, whether it's 5 items or 5,000.

The for Loop in PHP

A for loop is the best choice when you know exactly how many times you want to repeat something, like counting from 1 to 5.

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

A for loop has three parts separated by semicolons, all on one line. The first part, $i = 1, creates a counter variable and sets its starting value. The second part, $i <= 5, is the condition; the loop keeps running as long as this is true. The third part, $i++, increases the counter by 1 after every run. So this loop prints "Count: 1" through "Count: 5", then stops as soon as $i becomes 6, because the condition is no longer true.

The while Loop in PHP

A while loop is useful when you don't know in advance how many times you'll repeat something. It just keeps going as long as a condition stays true.

php
<?php
$count = 5;
while ($count > 0) {
    echo "$count...\n";
    $count--;
}
echo "Liftoff!\n";
?>

Here, $count starts at 5. PHP checks the condition $count > 0 before every run of the loop. Inside the loop, we print the current value of $count and then $count-- reduces it by 1. When $count reaches 0, the condition becomes false, the loop stops, and PHP moves on to print "Liftoff!". A while loop always checks its condition first, so if the condition starts out false, the code inside never runs.

The do-while Loop

A do-while loop is almost the same as a while loop, but it checks the condition after running the code, not before. That means the code inside always runs at least once, even if the condition is false from the start.

php
<?php
$tries = 0;
do {
    $tries++;
    echo "Attempt number $tries\n";
} while ($tries < 3);
?>

This code runs the block inside do { ... } first, printing "Attempt number 1", then checks the condition $tries < 3 afterward. Because the check happens last, do-while is a good fit for things like login attempts or menus, where you want to show something to the user at least one time before deciding whether to repeat it.

The foreach Loop (For Arrays)

foreach is the loop you will use most often once you start working with arrays. It automatically walks through every item in an array, so you never have to manage a counter yourself.

php
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
    echo "I like $fruit\n";
}
?>

Here $fruits is an array of three strings. The foreach loop takes each value in $fruits, one at a time, and stores it in the temporary variable $fruit for that pass through the loop. It runs once per item in the array, so this prints three lines, one for each fruit, and then stops automatically when there are no items left.

If your array has keys and values, like a list of prices, you can grab both at once:

php
<?php
$prices = ["apple" => 1.50, "banana" => 0.75];
foreach ($prices as $fruit => $price) {
    echo "$fruit costs $$price\n";
}
?>

This time $prices is an associative array, meaning each value has a named key instead of a number. Writing foreach ($prices as $fruit => $price) tells PHP: put the key in $fruit and the matching value in $price on each pass. This prints "apple costs $1.5" and "banana costs $0.75".

Stopping or Skipping With break and continue

Sometimes you need to exit a loop early, or skip just one pass without stopping the whole thing. PHP gives you two keywords for that: break, which stops the loop completely, and continue, which skips to the next pass.

php
<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 6) {
        break;
    }
    if ($i % 2 == 0) {
        continue;
    }
    echo "$i\n";
}
?>

This loop counts from 1 to 10, but as soon as $i equals 6, break exits the loop entirely, so numbers 6 and above never print. Before that, whenever $i is even, the line continue skips the echo for that pass and jumps straight to the next number. The end result is that only the odd numbers 1, 3, and 5 get printed.

Choosing the Right Loop

Loop typeBest used whenChecks condition
forYou know exactly how many times to repeatBefore each run
whileYou don't know the number of repeats in advanceBefore each run
do-whileThe code must run at least once no matter whatAfter each run
foreachYou are looping through every item in an arrayAutomatically, per item

Common Loop Mistakes Beginners Make

  • Forgetting to update the counter variable in a while loop, which creates an infinite loop that never stops.
  • Using = (assignment) instead of == or === (comparison) inside a condition, which sets a value instead of checking it.
  • Off-by-one errors, such as using < when you meant <=, so the loop stops one number too early.
  • Changing the array you're looping over from inside a foreach loop, which can cause confusing or unexpected results.

If your script ever seems to freeze or your browser tab keeps loading forever, an infinite loop is one of the most common causes. Always double check that the condition in a while or for loop can eventually become false.

Frequently asked questions

What is a loop in PHP?+

A loop is a block of code that repeats automatically until a condition tells it to stop. Instead of writing the same line of code many times, you write it once inside a loop, and PHP runs it again and again for you.

What's the difference between a for loop and a while loop in PHP?+

A for loop is best when you already know how many times you want to repeat something, since the counter, condition, and update all live in one line. A while loop is best when you don't know the number of repeats ahead of time and just want to keep going while a condition stays true.

When should I use foreach instead of for?+

Use foreach whenever you are looping through an array, such as a list of names or a set of prices. It automatically visits every item for you, so you don't need to track a counter or worry about how many items are in the array.

What causes an infinite loop in PHP and how do I fix it?+

An infinite loop happens when the condition in a while or for loop never becomes false, usually because the counter is never updated inside the loop. To fix it, make sure something inside the loop, like $i++ or $count--, actually moves the condition toward becoming false.

Can I use break and continue in every type of loop?+

Yes, break and continue work inside for, while, do-while, and foreach loops. break exits the loop immediately, while continue skips the rest of the current pass and moves on to the next one.

Now that you can repeat actions with loops, put them to work looping over real data structures in PHP.

Read: PHP Arrays for Beginners

Want a hand building your PHP project the right way from the start?

Talk to our team

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.