PHP examples: loops

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/25/08
-->
<?php
$max = $_GET["input"]; 
?>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<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://csci1101sp09.morris.umn.edu/~elenam/1101_spring09/loops/loops.php?input=13


Drawing 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/25/08
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<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://csci1101sp09.morris.umn.edu/~elenam/1101_spring09/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.