2.2 Working on a Series of Numbers
TechniqueUse a for loop to traverse all the numbers: <?php $x = 10; $y = 20; for ($i = $x; $i <= $y; $x++) { // $i will be every integer between $x and $y print "$i\n"; } ?> CommentsIn the example, all numbers from $x to $y are processed iteratively. This is helpful when, for example, you want to operate on coterminous sections of an array. Here is a short example: <?php $teachers = array("Sadlon", "Lane", "Patterson", "Perry", "Sandler", "Kelly", "Zung"); for ($i = 2; $i <= 5; $i++) { print "$teachers[$i]\n"; } ?> This example will print Patterson Perry Sandler Kelly If you want to loop through the numbers with noninteger intervals, modify the last argument of the for loop: <?php for ($i = $x; $i < $y; $i += .5) { // Loops through at half integer intervals } ?> Note Don't use a direct comparison operator ( == or != ) to break out of the loop. Because of rounding errors, such a test might not succeed, and you'll be stuck in that loop forever. |