|
Instructions | Troubleshooting
Difficulty: Easy
Time it takes to complete: 10 minutes
Rating: 3/5 (232 total votes)
(Rate this tutorial!)
Instructions:
Today we will learn about loops and how to make them. Surely, you will often need to repeat a certain piece of code, so that what loops are for. Luckily, in PHP we have 3 simple statements to do it:
- while: Loops through a block of code while a condition is true.
- do while: Executes a bunch of code, and then repeats it while a condition is true.
- for: Just loop a code x number of times.
- foreach: This one loops a bunch code for each element in an array.
Ok, let's explain each of them:
This statement will execute a block of code if and as long as a condition is true.
$i = 5;
while ($i<=15) {
echo "We're currently executing code number".$i." of the loop.<br />";
$i++;
}
This statement is very similar to while, except that it first executes the code no matter the condition, and THEN loops it while the condition is true.
$i = 0;
do {
$i++;
echo "We're currently executing code number".$i." of the loop.<br />";
}
while ($i<=10)
The for statement is used when you know how many times you want to repeat a loop.
for ($i=0;$i<=10;$i++) {
echo "I ate ".$i."chocolate bars!";
}
At last but not least, comes the foreach statement. This famous code is used to loop through arrays. The number of loops is based on how many elements the array contains.
$array = array("blue","red","purple","yellow","green");
foreach ($array as $colors => $number) {
echo "The ball has those colors: <br />"
echo $number." - ".$colors;
}
Congratulations! Now you know how to repeat code efficiently! See you in the next lesson, here at WebDevHQ.
Troubleshooting:
Please note, that it is possible to create loops that never end. Those are called infinite loops. They'll usually make your script crash. Just remember that you shouldn't be ashamed, since everyone that knows advanced PHP has made an infinite loop, even me. It's common, but with practice you'll make fewer of them, and spot them easily.
Remember that this statement has 3 parameters: The first one defines the variables, the second holds the condition, and the third explains what to do after it's excecuted (usually used for incrementing a variable).
By: Danneh
This script was entered into the database on Saturday 31 May, 2008 by spdaniel91
^^ Back to top ^^
|