The difference between loops

Mar 12, 2012   //   by phpfreelancer.biz   //   Blog, PHP Tutorial  //  No Comments

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
}

Leave a comment

Share This Post

RSS Wordpress News