PHP Loops

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any PHP Question?