All lessons

Loops

7 min · PHP

Repeat work without writing it out a hundred times.

PHP · Loops0/5 cleared

Enemy 1 of 5

The for loop, piece by piece

This for loop starts $i at 0, keeps going while $i is less than 3, and adds 1 each time, printing $i on every pass. Press Run to see 0, 1, 2.

Why this works

Loops let you repeat a block of code without copy-pasting it, which matters not just for saving typing, but because a repeated 100 times by hand is 100 chances to make a typo, and if you need to change the logic later you'd have to fix it everywhere instead of in one place.

A for loop packs three pieces of information into its parentheses, separated by semicolons: a starting point ($i = 0, run once before the loop begins), a condition checked before every iteration ($i < 3, the loop keeps running as long as this stays true), and a step that runs after every iteration ($i++, short for "increase $i by 1"). Together they answer three questions: where do I start, when do I stop, and how do I move forward each time.

The loop body, the code inside the { }, runs once per iteration, with $i holding a different value each time: first 0, then 1, then 2. As soon as the condition $i < 3 becomes false (when $i reaches 3), the loop exits immediately without running the body again.

You
Invisible Heisenbug
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.