Skip to main content

PHP Loops

Programs often need to do the same job many times: print every item in a list, or keep counting until a limit is reached. Instead of copying the code, you wrap it in a loop, and PHP runs it repeatedly for as long as a condition holds.

PHP offers four kinds of loop:

  • while - checks a condition first and keeps running the code while that condition stays true
  • do...while - runs the code one time without checking, then keeps repeating it while the condition stays true
  • for - repeats the code a set number of times
  • foreach - runs the code once for every element of an array

Each of these has its own lesson next, with working examples.