SITERAW

Loops in PHP

Welcome to another must-know pillar of PHP: loops! If there's one thing computers are really good at (besides making our lives both easier and more confusing), it's repeating instructions over and over again — and they never complain about it either!

Picture this: you're building the forum for your website. You want to display, say, thirty messages on a page. Now imagine having to write, "Display message 1 and the name of its author," "Display message 2 and the name of its author," "Display message 3...", and so on, all the way to 30. Tedious, right? Thankfully, PHP's got your back. With loops, you can say it just once: "Display 30 messages, and each time, show the name of the author too."

Now, don't worry — we're not building an entire forum just yet (it's a little early for that... hang around later in the course). But it is time to understand how loops work, because we'll use them a lot throughout this course. Luckily, they're not that complicated — you'll see!

The Theory Behind Loops

So, what is a loop, exactly? It's a structure that works kind of like a conditional (you know, if... else). In fact, you'll notice quite a few similarities with the chapter on conditions.

Simply put, a loop lets you repeat a group of instructions multiple times. It's a massive time-saver, super handy, and in many cases, downright essential.

Here's a quick diagram of how it works:

while (CONDITION_CHECK):
    - do A
    - do B
    - do C
    - [...]
    - back to CONDITION_CHECK

Here's what's going on inside that loop:

  • First, instructions A, B, and C are executed one after the other, top to bottom (just like normal).
  • Once done, PHP jumps back up to the beginning to check CONDITION_CHECK again.
  • If that condition is still true, it runs A, B, and C again.
  • Then checks the condition again... and again... and again...

You get the idea.

The only problem? If that condition never becomes false, the loop will never stop! It'll just keep chugging along forever and ever. Your browser might even beg for mercy.

That's why every loop — whether it's a while or a for — must have a condition. As long as the condition is true, the loop continues. The second it becomes false, the loop finally stops (whew!).

A Simple Loop: while

Let's start with the simplest kind of loop: while.

<?php
while ($keep_looping == true)
{
    // Instructions to execute inside the loop
}
?>

The keyword while can be translated as "as long as". In this case, we're telling PHP: "As long as $keep_looping is true, keep running these instructions."

The code you want to repeat goes between the curly braces {}. But hey, you're used to curly braces by now, right? They're pretty much everywhere in PHP. 😉

There's not a whole lot more to it. Still, let's walk through a couple of practical examples so you can see what loops are actually good for.

Let's say you've been punished (again) and your teacher has sentenced you to copy this line 100 times:

"I must not gaze at clouds while learning PHP."

Oof. Back in the day, you'd be stuck for hours writing that by hand. But now? PHP can do it in the blink of an eye! 😄

Check this out:

<?php
$line_count = 1;

while ($line_count <= 100) { echo 'I must not gaze at clouds while learning PHP.<br />'; $line_count++; // Same as: $line_count = $line_count + 1 } ?>

Output:

I must not gaze at clouds while learning PHP.
I must not gaze at clouds while learning PHP.
[...]

What's happening here?

The loop runs as long as $line_count is less than or equal to 100.

Inside the loop, we have two instructions:

  • A good old echo to display some text. Notice the <br /> tag at the end — that's HTML to force a line break. Since you know your HTML, that shouldn't come as a surprise: each line of text appears on its own line.
  • Then there's that strange-looking line: $line_count++;. What's that about? Well, as I noted in the comment, it's just a shorthand for adding 1 to the variable. That's called incrementation (a fancy term that simply means "add 1").

Each time the loop runs, the value of $line_count increases: 1, 2, 3, 4... all the way up to 100. Once it hits 101, the condition $line_count <= 100 becomes false, and the loop ends without running the echo one last time.

Boom! You've just written 100 lines in a flash. 🧙‍

Now, if your punishment were more severe — like writing it 500 times — no worries! Just tweak the condition: change it to "as long as it's less than or equal to 500" and you're good to go.

But here's a very, very important tip: Make sure your condition will eventually become false.

If it never does, your loop will run forever, and PHP will have a panic attack. Well, not quite — after around 15 seconds of relentless looping, PHP throws in the towel and gives you an error message, saying it's worked enough for today (there are ways to extend this time constraint, but I would recommend not touching it for now).

Variables in Loops

So, we've just seen how to print the same sentence hundreds of times with zero effort.

But hang on — is that actually useful? I mean, when would you need to do that on a website?

Well... not really. But as I mentioned earlier, we're learning basic techniques here — ones you'll reuse again and again as we move forward in this course. By the end, this loop system will allow you to tell PHP, "Hey, go ahead and display all the forum messages in one go." Of course, you'll need to learn a few more things to get to that point — but without loops, none of that would be possible. For now, all I'm asking is that you practice and understand how loops work.

Alright, how about another example just for fun? This time, instead of writing the same thing over and over, we'll make each line a little different. Variety is the spice of code, after all!

This example will help you clearly see how the value of a variable increases with each pass through the loop:

<?php
$line_number = 1;

while ($line_number <= 100) { echo 'This is line #' . $line_number . '<br />'; $line_number++; } ?>

Output:

This is line #1  
This is line #2  
[...]  
This is line #100

Simple, right? This example looks a lot like the previous one, except now we're printing the value of $line_number each time. That way, you can see it increasing little by little as the loop progresses.

Just so you know — remember that tip I gave you in the chapter on conditions? It works here too: you can close the PHP tag with ?>, write your text in plain HTML, and then reopen the PHP tag with <?php. That saves you from having to clutter your code with a bunch of echo statements. We'll be using this trick a lot throughout the course.

A More "Complex" Loop: for

Wait, don't panic! I promise — the word "complex" here does not mean "complicated."

The for loop is just another type of loop — a little more compact, a bit neater to write. That's why it's actually quite popular in real-life coding.

But here's the thing: for and while do the exact same job. Both are used to repeat instructions in a loop. Sometimes one might seem more convenient than the other — it really depends on the situation (and your personal taste, to be honest).

So, how does a for loop work? It looks a lot like while, except the first line is a bit... special. To help you compare the two, let's take our previous example and rewrite it using a for loop instead:

<?php
for ($line_number = 1; $line_number <= 100; $line_number++)
{
    echo 'This is line #' . $line_number . '<br />';
}
?>

Whoa — that's a lot happening in just one line! 😲

Okay, let's break down that for line, because that's the only new bit. The rest is exactly the same.

Right after the word for, you've got parentheses (yes, they're really there — I swear 😄). Inside those parentheses, there are three parts, separated by semicolons ;:

Let's walk through each one:

  • Initialization – This sets the starting value of the variable. Here, $line_number = 1.
  • Condition – As long as this condition is true, the loop continues running. Just like with while.
  • Incrementation – This part adds 1 to the variable after each loop. Super handy!

So yeah, the last two pieces of code do exactly the same thing. The only difference is that for condenses everything — initialization, condition check, and incrementation — into a single tidy line. Clean and efficient.

So, how do I choose between while and for?

Great question!

  • while is simpler and more flexible. You can use it for all kinds of loops. But... it's easier to forget things, like incrementing your variable.
  • for, on the other hand, is perfect when you know you'll be looping a specific number of times. It forces you to set everything up — including that all-important increment step — right from the start.

Take it from me: loops will save you a ton of time. Thanks to them, you can write PHP scripts in just a few lines of code — and still get them to crunch through mountains of work behind the scenes.

You'll especially appreciate loops once we dive into databases later in this course. Stay tuned — the magic's just getting started! 😉

How to Build a Website in HTML and CSS

Enjoyed this PHP & MySQL course?

If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.

More information