..while, for,
foreach, switch, or while block. For example, the following for loop will terminate if a
prime number is pseudo-randomly happened upon:
$primes = array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47);
for($count = 1; $count++; $count < 1000) {
$randomNumber = rand(1,50);
if (in_array($randomNumber,$primes)) {
break;
} else {
printf("Non-prime number found: %d
", $randomNumber);
}
}
?>
Sample output follows:
Non-prime number found: 48
Non-prime number found: 42
Prime number found: 17
Through the addition of the goto statement, this feature was extended in PHP 6 to
support labels. This means you can suddenly jump to a specific location outside of a
looping or conditional construct. An example follows:
for ($count = 0; $count < 10; $count++)
{
$randomNumber = rand(1,50);
if ($randomNumber < 10)
goto less;
else
echo "Number greater than 10: $randomNumber
";
}
108 CHAPTER 3 ?– PHP B ASICS
less:
echo "Number less than 10: $randomNumber
";
?>
It produces the following (your output will vary):
Number greater than 10: 22
Number greater than 10: 21
Number greater than 10: 35
Number less than 10: 8
The continue Statement
The continue statement causes execution of the current loop iteration to end and
commence at the beginning of the next iteration. For example, execution of the
following while body will recommence if $usernames[$x] is found to have the value
missing:
$usernames = array("grace","doris","gary","nate","missing","tom");
for ($x=0; $x < count($usernames); $x++) {
if ($usernames[$x] == "missing") continue;
printf("Staff member: %s
", $usernames[$x]);
}
?>
This results in the following output:
Staff member: grace
Staff member: doris
Staff member: gary
Staff member: nate
Staff member: tom
File-Inclusion Statements
Efficient programmers are always thinking in terms of ensuring reusability and
modularity.
Pages:
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192