Tag Archives: Loop

For vs Foreach

Foreach loops are more simple and appropriate for Associative arrays and when you don’t have to keep track of iterations. For Indexed arrays, For loops are more appropriate since their incrementers are nicely associated with the keys of Indexed arrays.

While vs Do While

While is an entry control loop where do while is an exit control loop so Do While loop runs at least once even when the condition is false.

Do While executes the condition one time less than While.

Foreach Loop

Foreach loop acts only on arrays and acts similar to For loop. Difference is you don’t have to define an incrementer and increment it. There is also no condition to evaluate. It would run for each item in the array and won’t run at all if the array is empty.

Syntax

foreach (array as value)  {
block of codes
}

Example

<?php
$array = array(1,2,3,4,5);
foreach($array as $value)
echo $value.” t”;
?>

Output

1 2 3 4 5

For Loop

Loops execute a block of code a specified number of times, or while a specified condition is true.

Syntax

for (initialize; condition; increment)
{
block of codes
}

Example

<?php
for($i=1;$i<=10;$i++){
echo $i.” t”;
}
?>

Output

1 2 3 4 5 6 7 8 9 10

Do While Loop

Do While loop is similar to While loop  But the difference is that its an exit control loop . That means the code in the loop will get executed at least once

Syntax

Do{
//Block of codes
}while (condition)

Example

<?php
$i=6;
do{
echo $i++.” t”;
}while($i<=5)
?>

Output

6

You can see that even though the condition is not true it will print the first value

While Loop

The while loop executes a block of code while a condition is true.

Syntax

while (condition) {
//Block of codes
}

Example

<?php
$i=1;
while($i<=10) {
echo $i++.” t”;
}
?>

Output

1 2 3 4 5 6 7 8 9 10