<html>
<body bgcolor=lightyellow>
<h1>Looping through arrays</h1>
<?php
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
$days_of_week = array ('Monday','Tuesday','Wednesday','Thursday','Friday');
$days_food = array ('Mon'=>'fish',
'Tue'=>'beef',
'Wed'=>'chicken',
'Thu'=>'pork',
'Fri'=>'veggy');
print "$days_of_week <br />"; //printing the array gives me nothing
print_r($days_of_week); //but I can dump the array using print_r()
print "<br />";
print_r($days_food);
print "<hr />";
// Loop through a regular array ------------------------------------------------
for ($i=0; $i < count($days_of_week); $i++) //loop through regular array
{ //count(array) = number of elements
print "The day $i is: $days_of_week[$i] <br/>";
}
print "<hr />";
// Loop through a regular array ------------------------------------------------
foreach ($days_of_week as $day) //loop through regular array
{ //assign each element value to $day
print "The day is: $day <br/>";
}
print "<hr />";
// Loop through a keyed array ------------------------------------------------
foreach ($days_food as $day => $meal) //loop through associative array
{ //assign each key to $day, and value to $meal //assign each element value to $meal
print "The meal for: <b>$day</b> is: $meal <br/>";
}
print "<hr />";
// Loop through a keyed array ------------------------------------------------
print "<table bgcolor=dddddd border=1>";
print "<tr bgcolor=tan><th width=75>Day</th><th width=75>Meal</th></tr>";
foreach ($days_food as $day => $meal) //loop through associative array
{ //assign each key to $day, and value to $meal //assign each element value to $meal
print "<tr><td>$day</td><td>$meal</td></tr>"; //place in HTML table
}
print "</table>";
print "<hr />";
?>
<?php include "../include.php"; ?> <!-- hyperlink to see the code -->
</body>
</html>