|
Flow Control Statements
This chapter describes:
- What are conditional statements.
- What are loop statements.
Conditional Statements
PHP supports most types of conditional statements used in other languages:
- "if ... elseif ... else" statements.
- "switch ... case ... default" statements.
Like other languages, "break" statements can be used in the "case" clauses to break out the "switch" statements.
Here is my standard test program for flow control statements, LibraryHours.php:
<?php # LibraryHours.php
# Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
#
$dateInfo = getdate();
$wDay = $dateInfo["wday"];
$weekDay = $dateInfo["weekday"];
$openHours = "open";
#
print "\nLibrary Hours with \"if\" statements:\n";
print " Today is: $weekDay\n";
if ($wDay == 0) {
$openHours = "closed";
} elseif ($wDay >= 1 && $wDay <= 5) {
$openHours = "open from 9:00am to 9:00pm";
} elseif ($wDay == 6 ) {
$openHours = "open from 9:00am to 5:00pm";
} else {
$openHours = "not at here";
}
print " The library is $openHours\n";
#
print "\nLibrary Hours with \"switch\" statements:\n";
print " Today is: $weekDay\n";
switch ($weekDay) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
$openHours = "open from 9:00am to 9:00pm";
break;
case "Saturday":
$openHours = "open from 9:00am to 5:00pm";
break;
case "Sunday":
$openHours = "closed";
break;
default:
$openHours = "not at here";
}
print " The library is $openHours\n";
?>
Output of the program:
C:\herong\php_20050402\src>php LibraryHours.php
Library Hours with "if" statements:
Today is: Saturday
The library is open from 9:00am to 5:00pm
Library Hours with "switch" statements:
Today is: Saturday
The library is open from 9:00am to 5:00pm
Loop Statements
PHP supports most types of loop statements used in other languages:
- "while" statements.
- "for" statements.
- "foreach" statements.
- "do ... while" statements.
Here is my standard test program for loop statements, PrimeNumbers.php:
<?php # PrimeNumbers.php
# Copyright (c) 2002 by Dr. Herong Yang
#
$upperLimit = 20;
#
print "\nCalculating prime numbers with \"for\" statements:\n";
for ($i=3; $i<$upperLimit; $i++) {
$isPrime = true;
for ($j=2; $j<=$i/2; $j++) {
$isPrime = $i%$j > 0;
if (!$isPrime) break;
}
if ($isPrime) print " $i is a prime number.\n";
}
#
print "\nCalculating prime numbers with \"while\" statements:\n";
$i = 3;
while ($i<$upperLimit) {
$isPrime = true;
$j = 2;
while ($j<$i) {
$isPrime = $i%$j > 0;
if (!$isPrime) break;
$j++;
}
if ($isPrime) print " $i is a prime number.\n";
$i++;
}
?>
Output of the program:
Calculating prime numbers with "for" statements:
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
19 is a prime number.
Calculating prime numbers with "while" statements:
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
19 is a prime number.
|