In this three-part tutorial, I show how we can include other files, explode text into chunks which are put into an array which we can search through. I chose to use a practical example and use a list of food items.
Part 2
Here are the sources used in this tutorial:
food.php
<?php //Food list $food = array(); $food[] = array(1, array("egg","eggs")); $food[] = array(6, array("gallons of milk","gallon of milk")); $food[] = array(4, array("loaf of bread","loaves of bread")); $food[] = array(2, array("tacos","taco")); $food[] = array(0.5, array("water bottle","water bottles")); $food[] = array(2, array("cup of flour","cups of flour")); ?>
tut014.php
<?php //PHP Tutorial 014 include("food.php"); ?> <form method="post" action="?"> Please put in your list of items, like 1 egg, 2 eggs, and seperate them by commas(","). <br /> <input type="text" name="list" size="100" /> <input type="submit" value="create list for printing" /> </form> <?php if(isset($_REQUEST['list'])){ $list = explode(",",trim(stripslashes($_REQUEST['list']))); $count = count($list); for($x=0; $x< $count; $x++){ $list[$x]= explode(" ",trim($list[$x]), 2); } $list2 = array(); $foodcount = count($food); for($x=0; $x< $count; $x++){ for($y=0; $y< $foodcount; $y++){ if(in_array($list[$x][1],$food[$y][1])){ $list2[] = array($list[$x][1], $food[$y][0], $list[$x][0]); } } } ?> <table width="300"><tr><th>Item Name</th><th>Unit Price</th> <th>Quantity desired</th></tr> <?php $newcount = count($list2); $total = 0; for($x=0; $x< $newcount; $x++){ echo "<tr><td>".$list2[$x][0]."</td><td align=\"center\">". $list2[$x][1]."</td><td align=\"center\">". $list2[$x][2].'</td></tr>'."\n"; $total += (real)$list2[$x][1]*(real)$list2[$x][2]; } ?> <th>Total is: </th><th>$<?php echo $total; ?></th><th> </th> </table> <?php } ?>