2

Maybe my question seems primary, But actually it is not. I claim that I can do everything is done with for() by while(), And conversely. So really when while() is useful when there is for()? I need to a example that I can do that by for() and I can not do that by while(). There is? I think there is not ...!

Here is the structure:

for (init counter; test counter; increment counter) {
    code to be executed;
}


init counter;
while (test counter) {
    code to be executed;
    increment counter;
}

see? they are exactly the same, Now I want to know why php has both of them?

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
  • 2
    See: http://stackoverflow.com/q/2698935/3933332 – Rizier123 Sep 14 '15 at 10:13
  • Yes!!! i think there is a one difference. If you know the number of iteration go for For loop otherwise While loop. And one more thing For loop is more readable and precise manner – Shashank Singh Sep 14 '15 at 10:42

3 Answers3

10

The difference is that the do while loop executes at least once because it checks for the loop condition while exiting. While is a entry controlled loop and do while is a exit control loop. Whereas in do while loop it will enter the loop and will then check for the condition.

while loop - used for looping until a condition is satisfied and when it is unsure how many times the code should be in loop

for loop - used for looping until a condition is satisfied but it is used when you know how many times the code needs to be in loop

do while loop - executes the content of the loop once before checking the condition of the while.

Insane Skull
  • 9,220
  • 9
  • 44
  • 63
0

They are exactly the same :

WHILE

INITIALIZE_1;
INITIALIZE_2;
...
INITIALIZE_N;
while(CONDITIONS) {
    // your block code
    ...
    # not only incrementation !!
    OPERATION_1;
    OPERATION_2;
    ...
    OPERATION_N;
}

FOR

for (INITIALIZE_1, INITIALIZE_2, ..., INITIALIZE_N ; CONDITIONS ; OPERATION_1, OPERATION_2, ..., OPERATION_N) {
    // your block code
    ...
}

for is more comprehensive for a humain, so he can see in one line : the initialization, conditions and operations, but there are other cases when while is more appropriate like :

while(NOT_QUIT_SIGNAL) { ... } vs for ( ; NOT_QUIT_SIGNAL ; ) { ... }

or

while(TRUE) { ... } vs for ( ; TRUE ; ) { ...}
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
0

You can use while(true) for a daemon (although there are definitely better languages for it), or a similar scenario, where you may want the script to run indefinitely.

Alternatively, while can be used with a predicate, or executing a function each time to check for a property.

while(functionCanExecute($someVar)) {
    //Do Stuff
}

This will be evaluated initially, and after every loop, to check if the while loop should run again.

Their underlying functionality may be very similar/the same, but there are certainly scenarios when it's easier to use one over the other.

MetalMichael
  • 130
  • 2
  • 10