11) PHP Loops

PHP Loops

Loops execute the same code multiple times.

While Loop:

Example:

Here loop will run until $i is less than 10.

Continue Keyword:

This condition will fail when $i is odd number. So when $i is odd the condition will fail and it will go back to the top of the loop.

Do…While Loop

The difference between while and do while loop is that do while loop is always executed at least once even if the condition never true.

Using for loop:

The main advantage of using a for loop that the chances of going to the infinite loop are less.

Example

foreach : Loop through Array

Accessing Array Values

Example

  • A foreach loop accesses each array element, and it is similar to for loop for indexed array.
  • foreach loop is only used when you have to process everything in order.
  • for loop is better when you don’t want to loop through the whole array.
  • foreach loop is mainly useful for an associative array.