Why is my While Loop not working?

Please tell me why my while loop is not working. I want it only to display the numbers in a given range (which in this example is from 3 to 6:

       $i == 3;
        while($i <= 6) {
            echo "The number is: $i <br>";
            $i++;
        } 

The echo result is:

The number is:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6

For some reason, it seems to be starting at 0 and not 3.

You are doing a comparison instead of an assignment on the first line.

Here is another way to do it.

foreach (range(3, 6) as $value) {
    echo "The number is $value<br>";
}

Thanks benanamen. That’s a pretty rookie error I made… not sure why I didn’t pick up on it.

Sponsor our Newsletter | Privacy Policy | Terms of Service