PHP examples: switch statement and loops
A switch statement
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
php switch statement
Author: Elena Machkasova elenam@morris.umn.edu
Last modified: 10/02/06
-->
<?php
$date = $_GET["input"];
?>
<html>
<head>
<title>
Days of the week
</title>
</head>
<body>
<h2>
<?php
switch ($date) {
case 0:
$day = "Sunday";
break;
case 1:
$day = "Monday";
break;
case 2:
$day = "Tuesday";
break;
case 3:
$day = "Wednesday";
break;
case 4:
$day = "Thursday";
break;
case 5:
$day = "Friday";
break;
case 6:
$day = "Saturday";
break;
default:
$day = "no such day";
}
print "Today is $day\n";
?>
</h2>
</body>
</html>
http://rynite.morris.umn.edu/~elenam/1101_fall06/php_examples/ifelse/switch.php?input=4
Simple examples of 'while' and 'for' loops
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
First program with loops
Author: Elena Machkasova elenam@morris.umn.edu
Last modified: 2/16/06
-->
<?php
$max = $_GET["input"];
?>
<html>
<head>
<title>
Printing numbers
</title>
</head>
<body>
<p>Printing numbers in increasing order</p>
<?php
$n = 1;
while ($n <= $max) {
print "$n ";
$n++; // I could use $n = $n + 1; instead
}
print "<br />\n";
?>
<p>Printing numbers in decreasing order</p>
<?php
$n = $max;
while ($n > 0) {
print "$n ";
$n--; // I could use $n = $n - 1; instead
}
print "<br />\n";
?>
<p>Printing numbers in increasing order with a 'for' loop</p>
<?php
for ($n = 1; $n <= $max; $n++) {
print "$n ";
}
print "<br />\n";
?>
<p>Printing numbers in decreasing order with a 'for' loop</p>
<?php
for ($n = $max; $n > 0; $n--) {
print "$n ";
}
print "<br />\n";
?>
</body>
</html>
http://rynite.morris.umn.edu/~elenam/1101_fall06/php_examples/loops/loops.php?input=13
Drwaing horizontal lines with a for loop
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Using a loop to draw lines of different lengths
Author: Elena Machkasova elenam@morris.umn.edu
Last modified: 2/16/06
-->
<html>
<head>
<title>
Using a loop to draw lines of different lengths
</title>
</head>
<body>
<p>Using a loop to draw lines of different lengths</p>
<?php
$max_length = 80;
$n = 7; // the number of lines
$length = $max_length;
for ($i = 1; $i <= 7; $i++) {
print "<hr style=\"width: $length%; align: center\"></hr>\n";
$length = 2 * $length / 3;
}
?>
</body>
</html>
http://rynite.morris.umn.edu/~elenam/1101_fall06/php_examples/loops/lines.php