Tutorial 20: For Loop

For Loops are a little trickier to wrap your head around, so hang in there!

The for loop is used when you know in advance how many times the script should run. w3schools

The syntax looks like so:

for (initialize counter; test if TRUE; increment counter) {

	// execute code


Essentially, the For Loop will:

  1. Initialize where the loop will start counting by adding a value to a variable
  2. Evaluate a certain condition to test if the condition is either TRUE or FALSE (if the condition is FALSE, the loop will stop running)
  3. Increment the value by 1 each time we loop through

So, if we want to have our For Loop spit out the numbers 0 to 20, we would code the following:

for ($a = 0; $a <= 20; $a++) {

	echo "Number: $a 
"; }

If coded correctly, this code should echo the numbers 0 to 20 on your screen, and stop at 20.

Feel free to experiment with the above For Loop with some PHP using the practice.php page provided in this folder.

Check out the final example
©2019 Brad Hussey