Loops

Download php eBook

Introduction

Loops are a fundamental aspect of programming. They allow programmers to create code that repeats for some given number of repetitions, or iterations. The number of iterations can be explicit (6 iterations, for example), or continue until some condition is met ('until Hell freezes over').

This topic covers the different types of loops, their associated control statements, and their potential applications in PHP.

Syntax

  • for (init counter; test counter; increment counter) { /* code */ }
  • foreach (array as value) { /* code */ }
  • foreach (array as key => value) { /* code */ }
  • while (condition) { /* code */ }
  • do { /* code */ } while (condition);
  • anyloop { continue; }
  • anyloop { [ anyloop ...] { continue int; } }
  • anyloop { break; }
  • anyloop { [ anyloop ...] { break int; } }

Remarks

It is often useful to execute the same or similar block of code several times. Instead of copy-pasting almost equal statements loops provide a mechanism for executing code a specific number of times and walking over data structures. PHP supports the following four types of loops:

  • for
  • while
  • do..while
  • foreach

To control these loops, continue and break statements are available.

Related Examples

Stats

666 Contributors: 19
Wednesday, August 2, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook