Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are do loops useful?

Tags:

php

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?

like image 403
Sweely Avatar asked Feb 01 '26 20:02

Sweely


1 Answers

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).

like image 183
Corbin Avatar answered Feb 04 '26 08:02

Corbin