LOOPS in PHP

When you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform this type of task .

 We have the following looping statements in php :-

  • while:- The while loop will print the loop index.  Then, the index will be checked with the while condition to process the code within the loop block. The loop will print the index value and increment it for each iteration. This will be continued till the while loop condition is satisfied.
PHP while statement - w3resource
while loop
  • do..while :- A “do while” loop is a slightly modified version of the while loop. If you recall from one of the previous lessons on while loop the conditional statement is checked comes back true then the code within the while loop is executed. If the conditional statement is false then the code within the loop is not executed necessarily run with a regular while loop .
PHP do while statement - w3resource
  • for :- The for loop is so easy to understand and it has a very simple structure to use it in programming. It has the initialization, conditional statement and increments/decrements in a single line .
PHP for loop - w3resource
  • foreach :- The foreach Loop is used to display the value of array. You can define two parameter inside foreach separated through “as” keyword. First parameter must be existing array name which elements or key you want to display.
C# | foreach Loop - GeeksforGeeks