Use for each to loop through an array and create a table : HTML Table « HTML « PHP






Use for each to loop through an array and create a table

 
$population = array('New York, NY' => 8008278,
                    'Los Angeles, CA' => 3694820,
                    'Chicago, IL' => 2896016);

$total_population = 0;
print "<table><tr><th>City</th><th>Population</th></tr>\n";
foreach ($population as $city => $people) {
    $total_population += $people;
    print "<tr><td>$city</td><td>$people</td></tr>\n";
    
}
print "<tr><td>Total</td><td>$total_population</td></tr>\n";
print "</table>\n";
  
  








Related examples in the same category

1.Creating an HTML table from array elements
2.Output a HTML table
3.Separate the city and state name in the array so we can total by state