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">
<!--
Exercise on if/else statements
Author: Elena Machkasova elenam@morris.umn.edu
Last modified: 2/13/06
-->
<?php
$date = $_GET["input"]; // Assuming February 2006
?>
<html>
<head>
<title>
Days of the week
</title>
</head>
<body>
<h2>
<?php
switch ($date % 7) {
	case 0: 
		$day = "Tuesday";
		break;
	case 1: 
		$day = "Wednesday";
		break;
	case 2: 
		$day = "Thursday";
		break;
	case 3:
		$day = "Friday";
		break;
	case 4:
		$day = "Saturday";
		break;
	case 5:
		$day = "Sunday";
		break;
	case 6:
		$day = "Monday";
		break;
	default: 
		$day = "no such day";	
}
print "Today is $day\n";
?>
</h2>
</body>
</html>

http://rynite.morris.umn.edu/~elenam/php_examples/ifelse/days_switch.php?input=16

A simple for/while loop


<!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/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/php_examples/loops/lines.php

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.