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. 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 parts. The first part is the condition part where we will generally provide conditions like counting up to specified number. The second part is the code we want to run in each step. Let’s look at the loop syntax.
for(START;CONDITION;STEP){
CODE
}
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 theCONDITION
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 its 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 the given array. So we do not need conditions or similar mechanisms. Foreach simply iterates over given sequential data. The syntax is like below.
foreach( ARRAY as KEY => VALUE ){
CODE
}
ARRAY
is sequential data where we loop throughKEY
is current steps keyVALUE
is current steps valueCODE
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.
$names = array( "ismail" , "ali" , "elif" );
foreach($names as $name){
echo $name."\n";
}
This will print all names one by one like below.
ismail ali elif
We see that there is only a value part but do not have a 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
1 thought on “Php For and Foreach Loops”