3

As you all probably know, do loops execute at least once, even if the statement is false — while the while loop would never execute even once if the statement is false.

When are do loops useful? Could someone give me a real life example?

Sweely
  • 386
  • 3
  • 15

3 Answers3

3

They're basically useful when you want something to happen at least once, and maybe more.

The first example that comes to mind is generating a unique ID (non sequentially) in a database. The approach I sometimes take is:

lock table
do {
    id = generate random id
} while(id exists)
insert into db with the generated id
unlock table

Basically it will keep generating ids until one doesn't exist (note: potentially an infinite loop, which I might guard against depending on the situation).

Corbin
  • 33,060
  • 6
  • 68
  • 78
0

The Do loop is very powerfull if you have to check multiple files etc. Due to the guarentee of iteration it will work all the way through.

do {
  if($integer > 0) { $nameoffile[0]++; } 
  else { $nameoffile[0] = $nameoffile[0].$integer; }
  $integer++;
} while(file_exists("directory/".$nameoffile[0].".".$nameoffile[1]));
Jonas m
  • 2,646
  • 3
  • 22
  • 43
0

Next to what has already been answered, you can do crude stuff like this with a do:

do
{
    if ($cond1) break;

    if ($cond2) continue;

    do_something();

} while(true/false);

Which is a modification of a switch loop, which allows continue. You can simulate goto similarities in case goto is not available and similar.

It must not make your code more readable, so it's often not suggested to do that. But it technically works.

hakre
  • 193,403
  • 52
  • 435
  • 836