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

  • The WordPress.com Year in Review (and Resolutions for 2018) January 3, 2018
    It was quite a year for the WordPress.com community, and we've got a lot to look forward to.
  • Managing Your Blog On a Mobile Device December 13, 2017
    A few enhancements we've added to the iOS and Android apps for easier blogging.
  • New Premium Themes: Small Business and Photo Blog December 7, 2017
    Introducing two new premium themes: Small Business, made for your entrepreneurial endeavors, and Photo Blog, designed to make your photography shine.
  • Updated Privacy Policy December 4, 2017
    As part of our commitment to privacy and transparency, we’re updating our Privacy Policy. We want to give you more information about how we collect and use personal information — in a more organized and readable format. “Your privacy is critically important to us.” These are the first words of …
  • Update Your Avatar on WordPress.com October 12, 2017
    Manage, upload, and edit your profile photo at wordpress.com/me.
  • A New Media Picker for the iOS WordPress App October 9, 2017
    Sometimes it’s the extra touches that make all the difference; on your website, that’s the photos and video that give your content life. You asked for streamlined access to your media library and the camera and photos on your device, to make uploading and inserting photos and videos easier. We …