100Part IPHP: The Basicscontinue; print( $x ); } prints: (Affordable web design)
Thursday, August 9th, 2007100Part IPHP: The Basicscontinue; print( $x ); } prints: 2 4 6 8because the effect of the continuestatement is to skip the printing of any odd numbers. Using the breakcommand, the programmer can choose to dispense with the main termina- tion test altogether. Consider the following code, which prints a list of prime numbers (thatis, numbers not divisible by something other than 1 or the number itself): $limit = 500; $to_test = 2; while(TRUE) { $testdiv = 2; if ($to_test > $limit) break; while (TRUE) { if ($testdiv > sqrt($to_test)) { print $to_test ; break; } // test if $to_test is divisible by $testdivif ($to_test % $testdiv == 0) break; $testdiv = $testdiv + 1; } $to_test = $to_test + 1; } In the preceding code, we have two whileloops the outer loop works through all the num- bers between 1 and 500, and the inner loop actually does the testing with each possible divisor. If the inner loop finds a divisor, the number is not prime, so it breaks out without printing any- thing. If, on the other hand, the testing gets as high as the square root of the number, we cansafely assume that the number must be prime, and the inner loop is broken without printing. Finally, the outer loop is broken when we have reached the limit of numbers to test. The resultin this case is a list of primes less than 500: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 8389 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449457 461 463 467 479 487 491 499Notice that it is crucial to this code that breakinterrupt the inner whileloop only. There is another iteration construct, called foreach, which is used only for iterating overarrays. We cover it in Chapter 9. Cross- Reference08
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.