2.2 Working on a Series of Numbers


2.2 Working on a Series of Numbers

You want to do an operation on a series of numbers from $x to $y .

Technique

Use 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"; } ?> 

Comments

In 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.




PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net