Loops are used when you want to execute some code a bunch of times. Ova, and ova, and ova again.
Let’s start with a while loop. We’ll declare the variable i equal to 100. Then the keyword while, some parenthesis, and a set of braces. Inside the parenthesis, we’ll put our condition, i is greater than zero. Inside the braces, put "print num bottles of beer on the wall". Then i minus minus.
The while loop will do something over and over again as long as the condition is true. In this depressing example, the number of bottles of beer on our wall will count down to zero. Once i is equal to zero, our loop ends.
There is another loop syntax called the for loop.
This loop example contains three statements, the first is the initial value, followed by the condition, followed by a statement to increment the initial condition. So, let’s type the keyword for, some parentheses, inside those put i equals 0, semicolon, i is less than 10, semicolon, and i plus plus. Then we’ll add some braces, and put the statement "print, PHP gets me hot."
I bet you can guess what’s going to happen next. This for-loop will print “PHP gets me hot” 10 times.
The final variation is the foreach loop. While the previous two examples are common in pretty much any programming language, the foreach loop is special to PHP. This loop is great if you have an array full of items and you want to go through them one by one. It is by far the most common method used in PHP to loop over things.
Let’s go back to our babe array from the last lesson.
$babe = array(‘bust’ => 32, ‘waist’ => 24, ‘hips’ => 37);
Next, we’ll put the foreach keyword then babe, the keyword ‘as’, then value. Slap on a set of braces, and inside those, put print value and add a BR tag for good measure. The foreach loop does what’s on the label, it loops over each value in the babe array and gives us the value to do as we please.
What if we wanted to loop through the array, but get the keys AND values? That would be:
Foreach, babe as measurement, arrow, then value. This gives us access to the keys and values, so we could change our print statement to this. (gesture)
Ok, so now you’ve got a basic understanding of how php works, in the next lesson we’re going to talk about functions. And we’ll see if you can still function.