4

I am searching advantage of using Do While, most of blogs and tutorials say its depends on requirement, without that is there any advantage we get from Do While ?

<?php
$i = 0;
do {
     echo $i;
} while ($i > 0);
?>
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
Joel Campbell
  • 89
  • 2
  • 4
  • All three loop constructs can do the same things. The advantage is that depending on what exactly you want to do, one of them usually results in more readable ("natural") code than the others. – Jon Aug 16 '13 at 11:33
  • The advantage is that the code within a `do/while` will always be executed at least once (one or more times); compared with code within a `while`, which will be executed zero or more times. Circumstances dictate which one you should use – Mark Baker Aug 16 '13 at 11:34

6 Answers6

8

That's funny. Today was one of those days when I needed a do while loop. It was kind of like this: I wanted to generate a number, but it had to pass a test.

With a while loop it would look something like this:

$num = generateRandomNumber();
while (!numberMeetsRequirements($num)) {
    $num = generateRandomNumber();
}

As you can see, one line is repeated, once inside and once outside the loop. In this particular example, you can avoid this by using a do-while loop:

do {
    $num = generateRandomNumber();
} while (!numberMeetsRequirements($num));

But like the others already said: It really depends on what you are doing. The code above is only an example.

Butt4cak3
  • 2,389
  • 15
  • 15
4

There's no advantage. while is a pre-conditioned loop, and do..while is post-conditioned loop. That means - in while a condition is checked before iteration, and in do..while - after iteration.

Therefore, in do..while loop body will be executed at least once - so it can not be used if you're iterating by something, which can have zero repeating (for example, count of rows in select from database).

Note, that due to structured program theorem any program could be written only with if and while. So, in general, there's no need in do..while statement. You always can replace it with while.

Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • Why do I think that every case you need a condition to be executed once no matter what the statement is, can be achieved without do{} aswell? – Royal Bg Aug 16 '13 at 11:40
  • Yes, and what's the question? Or what do you mean? – Alma Do Aug 16 '13 at 11:42
  • I mean is there really a practical case where do{}while is necessary? I have seen it very rarely in real code nowadays. Is there an advantage using it, rather than make it fit without using do{}? – Royal Bg Aug 16 '13 at 11:44
  • Due to structured program theorem (http://en.wikipedia.org/wiki/Structured_program_theorem) any program could be written only with `if` and `while`. So, in general, there's no need in `do..while` statement. You always can replace it with `while`. – Alma Do Aug 16 '13 at 11:48
  • kudos go to @alma-do-muri - his post should be the canonical answer to the initial question. +1. regards, Gadoma – Gadoma Aug 16 '13 at 11:50
  • Your phrase `make it fit` expresses the reason.... do/while doesn't need to be `made to fit` a condition.... but no, it isn't necessary in the same way as `for` or `foreach` loops aren't necessary; but they can make the code easier to read in certain circumstances without needing to artificially create conditions – Mark Baker Aug 16 '13 at 11:50
  • Of cause they can. And using functions or OOP also can. I mean that a theorem gives only a statement that it _could_ be replaced. It does no mean that it _should_ be replaced. – Alma Do Aug 16 '13 at 11:53
  • @MarkBaker, the question was in the practical cases, I mean, you, as a developer, for example, do you use do{}while? Because in many of the occasions in modern web applications, I don't see do{}while, but only while. On other hand, I don't see for() to loop through arrays by their count, but I see foreach(). – Royal Bg Aug 16 '13 at 11:56
  • @RoyalBg regarding the "foreach" loop - isn't it obvious that in OOP you'll see more of it than the "for" loop ? Most often you'll be iterating objects not arrays, right? – Gadoma Aug 16 '13 at 12:04
  • There have been circumstances where I've used do/while; yes.... e.g. `do { $operand = array_pop($operand); } while (is_array($operand));` for popping values off a formula evaluation stack, when I want at least one entry (and possibly more) popped – Mark Baker Aug 16 '13 at 12:05
  • Using `foreach` against an array means you won't have any problems with associative arrays, or enumerated arrays with gaps in the sequence that could be a problem when using a `for` loop.... but each type of looping structure has its place; even though you only actually need one looping structure and can make anything else fit that structure – Mark Baker Aug 16 '13 at 12:08
  • If I am not wrong, PHP has key() function, which get's the key of an array, even it's assoc. You can use for loop even in that way. The question was in the matter of way of codding. Which one is more prefered nowadays. Do you use do{}while often, or you got used to use another way to have only while loops, etc. It was just collecting opinions which is more widespread or good/bad practice. However, I think I understood you :) Thank you – Royal Bg Aug 16 '13 at 12:11
  • @MarkBaker you cant use a foreach loop directly on an object that doesnt implement the iterator interface. – Gadoma Aug 16 '13 at 12:11
  • @Gadoma - The one looping structure that I'm talking about isn't `foreach`... you can simulate all other looping structures (including foreach) with a `while` loop, so that's the only one that a language actually needs to implement. – Mark Baker Aug 16 '13 at 12:13
  • Sure, I was just referring to your for/foreach comments :) – Gadoma Aug 16 '13 at 12:14
0

A Do While will always run once as the condition is only checked after the first run

Where a While Do will only run if your condition matches as it is checked first

Anigel
  • 3,435
  • 1
  • 17
  • 23
0

The main thing is that the statements inside the loop are executed at least once where in most other constructs they might never be executed.

Kris
  • 40,604
  • 9
  • 72
  • 101
0

do { >>command<< } while () <-- command will be exectued at least one time

while () { >>command<< } <-- command will only be executed if while condition is true

MS_SP
  • 218
  • 2
  • 9
0

You can implement any algorithm using a for, while and do-while loop interchangeably. However, following the flow of logic may push you towards using one loop over the other.

A prime example of when using a do-while loop is more appropriate (based on the flow of logic) is in the implementation of a bubble sort. The description of the algorithm can be found here, in short you know that you will need to at least iterate through the array once (seeing as the best-case for bubble sort is O(n), where n is the length of the array). The implementation is as follows:

$arr = array( 10, 5, 6, 1, 3, 2, 7, 8, 9, 4 );
$arr_len = 10;
$swapped;

do {
  $swapped = false;

  for ( $i = 0; i < ( $arr_len - 1 ); $i++ ) {
    if ( $arr[ i ] > $arr[ i + 1 ] ) {
      $temp = $arr[ i ];

      $arr[ i ] = $arr[ i + 1];
      $arr[ i + 1 ] = $temp;

      $swapped = true;
    }
  }
} while ( $swapped == true );

My PHP is very rusty, if there is a syntax error do let me know.

Jacob Pollack
  • 3,703
  • 1
  • 17
  • 39