Lesson 10 PHP while loops

While loops repeat code as long as a condition is true. A simple example counts from 0 to 4 by checking if i is less than 5 each time. Avoid infinite loops like while(true), and when waiting for something external, use a counter or timeout instead of a condition that might never become false.
Chapters
Hello and welcome again. In this tutorial, we are going to be learning about while loops. While— while you— sorry, tongue-tied. While loops basically repeat the same function over and over until the variable you are checking for changes. Let's take a look at one, shall we? Let's create an int called i with a value of 0. Let's do while i is less than 5, we will run this script. We'll echo out i and a newline, and then we'll increase i. Now basically what this means is while i is less than 5, Then we will run this script. And basically once it hits this, it will basically go back up to here and rerun it. But since we also have this little i++ here, it will increase our i 1. So then after about 5 runs of this, it will stop because i will no longer be less than 5. Let's run it. And we have 0, 1, 2, 3, 4, because 0 counts as 5. And basically that is all. One quick warning though. Do not put yourself into an infinite loop. While True, something like this where a value always returns true, will run forever. Let's take a look at that. And it will keep on printing while it's loading. This page will never be done loading. Yeah, that's bad because our script is still executing. Oh my, we'll just stop that. Okay, that's pretty much all for while. Uh, just a quick little tip, if you're like waiting for something like some other function or to change a variable and there's a chance that the variable change could fail due to some sort of database connection, whatever you're trying to change, I would recommend using i instead of checking for the variable. So I mean like, uh, have it like a number of attempts to check for the variable before it times out. Or yeah, you create sort of a little fake timeout script, and, uh, so then you don't end up running forever because you are waiting on your function to update a variable, but yet it really won't be updating the variable because it failed the first time. So yeah, that's pretty much all it is for Wiles, and hope to see you next time. Bye.










