Modifying an array with foreach() : foreach « Statement « PHP






Modifying an array with foreach()

 
<?
$meals = array('A' => 1,
               'B' => 4.95,
               'C' => 3.00,
               'D' => 6.50);

foreach ($meals as $dish => $price) {
    $meals[$dish] = $meals[$dish] * 2;
}

foreach ($meals as $dish => $price) {
    printf("The new price of %s is \$%.2f.\n",$dish,$price);
}
?>
  
  








Related examples in the same category

1.Foreach Demo
2.Looping through an Enumerated Array
3.Array element order and foreach()
4.Iterating through a multidimensional array with foreach()
5.Using foreach() to Iterate Through an Array
6.Using foreach() with numeric arrays
7.Displaying the contents of an array using a loop
8.Iterating Through Object Properties
9.Implementing the traversable Iterator