When coding PHP, loops can be fantastic! Basically, you can write a piece of code to repeat itself again and again until a certain condition has been met. There are a few types of loops in PHP, in this lecture we'll learn about While Loops.
Here's how a while loop works:
while (condition is true) { // execute code }
At this point, you probably have no idea how to actually use a while loop in PHP. That's okay. Let's dive into how you actually use it.
Let's say you want PHP to echo the numbers from 10 to 20. First you need to set a variable with your starting number:
<?php // Set a variable with your starting number $startingNum = 10; ?>
Then you need to start your while loop with a condition. In this case, we want our condition to say "while my starting number ($startingNum
) is less than or equal to 20, the condition is true".
To help clarify — as long as $startingNum
is less than or equal to 20, keep on looping!
<?php // Set a variable with your starting number $startingNum = 10; // While $startingNum is less than or equal to 20 while ($startingNum <= 20) { // execute code } ?>
You may be thinking: "our starting number is 10, it will always be less than 20, dumbo!".
Well, each time we loop through our function, we will tell PHP to increment our starting number by 1. Therefore, eventually our starting number will be equal to 20!
Our condition says to stop looping once our starting number is larger than 20. We need to do this to prevent an infinite loop — something you most definitely don't want! An infinite loop means your function will literally run forever, which can freeze up your computer.
So, let's tell PHP to echo our $startingNum
variable, then increment the variable by 1:
<?php // Set a variable with your starting number $startingNum = 10; // While $startingNum is less than or equal to 20 while ($startingNum <= 20) { // Echo the variable on the screen // We'll also concatenate a
tag at the end echo $startingNum . "
"; // Then increment the value by 1 $startingNum++; } ?>
In PHP, you can increment and decrement variables like so:
$a++;
adds 1 to the value of the variable $a
each time through$a--;
subtracts 1 from the value of the variable $a
each time through
If coded correctly, this code should echo the numbers 10 to 20 on your screen, and stop at 20. Keep in mind, you can use any of the operators we've used in our past lectures as the conditions that need to be met in the while loop.
Feel free to experiment with the above While Loop with some PHP using the practice.php page provided in this folder.