Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

$deutsch_Day = "Donnerstag";
break;
case "Friday":
$deutsch_Day = "Freitag";
break;
case "Saturday":
$deutsch_Day = "Samstag";
break;
default:
// It must be Sunday
$deutsch_Day = "Sonntag";
}
/*
* Print today's English and German names
/
print("

German Lesson: Day of the Week

\n");
print("In English: $english_Day.
\n");
print("In German: $deutsch_Day.
\n");
?>


is much more useful than in other languages. If you have experience with BASIC, you
might wonder if PHP's switch statement allows cases to contain ranges. It doesn't. It's
probably best to code this situation with an if-elseif-else statement.


Loops


Loops allow you to repeat lines of code based on some condition. You might want to read
lines from a file until the end is reached. You might want to print a section of HTML
code exactly ten times. You may even wish to attempt to connect to a database three
times before giving up. You can do all of these things with loops.


The while Statement


The simplest of loops is the while statement. When first reached, the expression is
evaluated. If false, the code block is skipped. If true, the block is executed and then
control returns to the top where, again, the expression is evaluated. Figure 3-4 shows the
structure of a while statement.


Figure 3-4. The while statement.

A while loop is useful when you aren't sure exactly how many times you will need to
iterate through the code—for example, when reading lines from a file or fetching rows
from a database query. For the sake of a simple demonstration, let's examine some code
that prints the days of the week between now and Friday.

Free download pdf