Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between loops

Tags:

loops

php

It's about PHP but I've no doubt many of the same comments will apply to other languages.

Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?

for ($i = 0; $i < 10; $i++)
{
    # code...
}


foreach ($array as $index => $value)
{
    # code...
}


do
{
    # code...
}
while ($flag == false);
like image 940
Teifion Avatar asked Aug 22 '08 16:08

Teifion


People also ask

What is difference between loops in C?

A for loop is a single-line command that will be executed repeatedly. While loops can be single-lined or contain multiple commands for a single condition. Both the for loop and the while loop are important in computer languages for obtaining results. The condition is met if the command syntax is correct.

What are different types of loops in explain?

Types of LoopsA for loop is a loop that runs for a preset number of times. A while loop is a loop that is repeated as long as an expression is true. An expression is a statement that has a value. A do while loop or repeat until loop repeats until an expression becomes false.


1 Answers

For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet

The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;

for ($i = 0; $i < 10; $i++)
{
        # code...
}

Same thing done with while loop:

$i = 0;
while ($i < 10)
{
    # code...
    $i++
}

Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block

do
{
        # code...
}
while ($flag == false);

foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index.

foreach ($array as $index => $value)
{
        # code...
}

You could do the same thing with while loop, like this

while (current($array))
{
    $index = key($array);  // to get key of the current element
    $value = $array[$index]; // to get value of current element

    # code ...  

    next($array);   // advance the internal array pointer of $array
}

And lastly: The PHP Manual is your friend :)

like image 153
Imran Avatar answered Sep 21 '22 22:09

Imran