Search code examples
phploopswhile-loopcycle

Why while loop works like this?


I thought, that I understand something in programming... But I don't understand the example below...

<?php
$i = 0;
$j = 0;
while($i<5){
    while($j<5){
        echo "$i $j; ";
        $j++;
    }
    $i++;
}

The output I expect: "0 0; 0 1; 0 2; 0 3; 0 4; 1 0; 1 1; 1 2; 1 3; 1 4; 0 0; 2 1; 2 2; 2 3; 2 4; 3 0; 3 1; 3 2; 3 3; 3 4; 4 0; 4 1; 4 2; 4 3; 4 4;".

The output I get: "0 0; 0 1; 0 2; 0 3; 0 4;".

Why is that?


Solution

  • You set j to 0 once, outside of both loops.

    By the time i goes to 1, j is already 5 and you do nothing to set it back to 0.

    $i = 0;
    while($i<5){
        $j = 0; // $j should be here
        while($j<5){
            echo "$i $j; ";
            $j++;
        }
        $i++;
    }