Nested Loops

Any type of loop can be enclosed inside any other loop creating a nested loop. The example below prints a tip table.
Cost10%15%20%
 10.00 1.00 1.50 2.00
 20.00 2.00 3.00 4.00
 30.00 3.00 4.50 6.00
 40.00 4.00 6.00 8.00
 50.00 5.00 7.5010.00
 60.00 6.00 9.0012.00
 70.00 7.0010.5014.00
 80.00 8.0012.0016.00
 90.00 9.0013.5018.00
100.0010.0015.0020.00

The code:
echo '<table width="200" border="1"><tr><th scope="col">Cost</th><th scope="col">10%</th><th scope="col">15%</th><th scope="col">20%</th></tr>';
$cost=10;
while($cost<=100) {
	if($cost<100) $space="&nbsp;"; else $space="";
	echo '<tr><td>'.$space.number_format($cost,2).'</td>';
	for($per=.10;$per<=.20;$per+=.05) {
		$tip=$cost*$per;
		if($tip<10) $space="&nbsp;"; else $space="";
	    echo '<td>'.$space.number_format($tip,2).'</td>';
	} //each percentage
	echo '</tr>'; //end the row
	$cost+=10;
}
echo '</table>'; 

Note: &nbsp; is a non-breaking space.

Experiment: This script used a for and a while loop, but it could have been written with any of the types of loops. Try writing it another way, then try creating a completely different table.


INDEX, Loops: Introduction, Loops: while, Loops: do while, Nested Loops
Next lesson: ArraysMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Nested Loops