Loops are useful for many things. For one, they allow you to produce detailed lists of data much faster and easier than you could by manually typing them. Loops are also extremely useful when used with arrays of data.
So what exactly does a loop do? A loop is used to perform the same task until a specific condition is reached. There are a few different kinds of loops in PHP, like in any other programming language. In this tutorial I will cover the while, foreach, and for loops.
while loops
I will start with while loops as these are the most basic kind of loop in PHP. Here is what a while loop looks like:
<?php
|
|
The structure of a while loop looks very similar to an if statement. PHP checks to see if what is inside of the parenthesis evaluates to true. If so, everything that is nested inside of the curly braces is performed. PHP continues to perform those tasks until the condition in the parenthesis evaluates to false.
Here is a very basic example of how to use a while loop:
<?php
|
|
Alright, what's happening here is pretty simple. First off, we declare a variable, $i, that holds the value of 1. This variable is what we'll use for the conditional of our while loop as well as to echo out our numbers from 1 to 10.
We then tell PHP that we want it to perform a loop. Our loop will continue so long as the value of $i is less than or equal to 10 ($i <= 10). Each time PHP iterates through the loop we tell it to echo out our variable and then increment it by one. That's it, try running this script yourself to see what happens.
Go on to the next page to read about foreach loops.
| Discuss Tutorial: Using Loops in PHP | 4 Comments |
I used it for my birthday drop-down boxes 
!!
























