PHP Loops - Taleem Dunya

Lecture 03

PHP Loops

Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. PHP supports four different types of loops.

  • While  loops through a block of code as long as the condition specified evaluates to true.
  • Do While the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
  • For loops through a block of code until the counter reaches a specified number.
  • Foreach  loops through a block of code for each element in an array.

For Loop in PHP

For loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times.
The parameters of for loop have following meanings:

It is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.

In the beginning of each iteration, condition is evaluated. If it evaluates to true, the loop continues and the nested statements are executed. If it evaluates to false, the execution of the loop ends.

It updates the loop counter with a new value. It is evaluate at the end of each iteration.


Foreach Loops

The foreach loop in PHP is a control structure that allows you to iterate over arrays and objects in a simple and straightforward manner. It is particularly useful for traversing associative arrays and objects where you need access to both keys and values.