Php – For and Foreach Loops – POFTUT

Php – For and Foreach Loops

[rps-include post=6522]

Loops are used to iterate over some block of code again and again in given conditions. We can specify the code which will loop and the conditions we want to check or met. Php supports different loop types but for and foreach loops are the most popular and useful loop in Php and most of the other programming languages. In this tutorial we will learn these loop mechanisms

For Loop

For loop have two main part. First part is the condition part where we will generally provide condition like counting up to specified number. Second part is the code we want to run in each step. Let’s look the for loop syntax.

  • START runs only once when the loop starts and generally used to define, initialize counter or similar variables.
  • CONDITION is checked in each step of the loop and the loop continue unless the CONDITION is true.
  • STEP is issued in each loop and generally used to change defined value or variable.
  • CODE will run in each step or loop.

Now time for example. We will simply count from 1 to 10 with the following for loop. In this loop we initialize the $counter variable and increase it in each step. We also check $counter value whether it s equal or less than 10 .

Foreach Loop

Foreach loop is a bit different from for loop. Foreach loop iterates over given array. So we do not need conditions or similar mechanisms. Foreach simply iterates over given sequential data. Syntax is like below.

LEARN MORE  Powershell ForEach Loop Statement Tutorial with Examples

  • ARRAY is sequential data where we loop through
  • KEY is current steps key
  • VALUE is current steps value
  • CODE is the part where will run in each step

In this example we will iterate over an array which is named $names and contains some names.

This will print all names one by one like below.

We see that there is only value part but do not have key part. We can use both key and value like below. We will iterate over an associative array in this example.

This code will output like below.

[rps-include post=6522]

1 Response

  1. 30/07/2017

    […] PHP For and Foreach Loop Statements […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)