Created
August 27, 2012 19:56
-
-
Save recck/3491772 to your computer and use it in GitHub Desktop.
Week 2 - Day 4 - PHP Loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* for loops | |
* where to start; when to continue; how to step through | |
**/ | |
for($i = 0; $i < 10; $i++){ | |
// start at i = 0 and continue until i is >= 10 | |
echo $i; | |
// you would expect: 0123456789 | |
} | |
/** | |
* while loops | |
* execute this code while this is true | |
**/ | |
$i = 0; # remember to set these variables if you're using a while loop involving numbers | |
$j = 5; | |
while($i < 10 && $j < 10){ | |
// so while i and j are both less than 10, print out the sum of i and j | |
echo $i*$j . " "; | |
// you would expect: 0 6 14 24 36 | |
$i++; | |
$j++; | |
// REMEMBER to increment the variables inside the conditional | |
// or else you would be stuck in an infinite loop | |
} | |
/** | |
* do-while loops | |
* do the following code, while this is true | |
**/ | |
$i = 0; # remember to set this variable if you're using a do-while involving numbers | |
do { | |
echo $i; | |
// you would expect 0123456789 | |
$i++; | |
} while($i < 10); | |
/** | |
* breaking out of a loop | |
**/ | |
for($i = 0; $i < 10; $i++){ | |
if($i == 5){ | |
// whenever i is equal to 5, stop the loop and just break out of it! | |
break; | |
} | |
echo $i; | |
// expected 01234 | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment