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 .

for( $counter=1; $counter<=10 ; $counter++ ){

echo $counter;


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.

foreach( ARRAY as KEY => VALUE ){
  • 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
LEARN MORE  Linux Bash For Loop Range Examples

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

$names = array( "ismail" , "ali" , "elif" );

foreach($names as $name){
echo $name."\n";

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.

$names = array ("ismail"=>"baydan" , "ali" => "baydan" , "elif" => "baydan");

foreach($names as $name=>$surname){

echo $name." ".$surname."\n";


This code will output like below.

ismail baydan
ahmet baydan
elif baydan

[rps-include post=6522]

1 thought on “Php – For and Foreach Loops”

Leave a Comment