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.
PHP loops for beginners explained simply: learn for, while, do-while, and foreach with copy-paste examples and line-by-line breakdowns.
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.
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.
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
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.
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
$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.
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
$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.
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
$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
$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".
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
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.
| Loop type | Best used when | Checks condition |
|---|---|---|
| for | You know exactly how many times to repeat | Before each run |
| while | You don't know the number of repeats in advance | Before each run |
| do-while | The code must run at least once no matter what | After each run |
| foreach | You are looping through every item in an array | Automatically, per item |
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.
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.
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.
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.
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.
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 BeginnersWant a hand building your PHP project the right way from the start?
Talk to our teamOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
PostgreSQL ILIKE explained for beginners: search text without worrying about case, learn % and _ wildcards, and copy simple examples you can run today.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.