1. Home
  2. Computing & Technology
  3. PHP / MySQL

Loops in PHP

By Angela Bradley, About.com

What is a loop?:

You've heard the term loop before, but you may not really be sure what it is. A loop is a series of commands that will continue to repeat over and over again untill a condition is met. For example, let's say you have the names of people in an array, and you wanted print a list of all of the names. You could setup a loop that would print the first persons name, and then move on to the next and print her name, etc (the continuing to repeat itself part.) The condition would be that it stops once all of the names have been used.

FOREACH Loop:

FOREACH Loops are used to do something specific to each value in an array. So for example if an array contained 5 pieces of data, then the FOREACH loop would execute 5 times. Read about FOREACH Loops

FOR Loop:

A FOR loop continues to process a block of code until a statement becomes false, and everything is defined in a single line, making it somewhat different to a WHILE loop. Read about FOR Loops

WHILE Loops:

Basically what a WHILE loop does is evaluate a statement as true or false. If it is true it executes some code and then alters the original statement and starts all over again by re-evaluating it. It continues to loop through the code like this until the statement becomes false. Read about WHILE Loops

Loop Decisions:

While inside the loop, decisions about what to execute are sometimes made based upon the current loop data. The most common ways to do this are to use an IF/ELSE statement, or to use SWITCH to make a Switch Loop.
Explore PHP / MySQL
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Learn PHP
  5. For Loops - While Loops - Switch Loops

©2009 About.com, a part of The New York Times Company.

All rights reserved.