Thursday, February 24, 2011

Using foreach to walk through an array

foreach walks through the array one value at a time. The current key and value of the array can be used in the block of statements each time the block executes. The general format is

foreach( $arrayname as $keyname => $valuename)
{
     block of statements;
}

For instance, the following foreach statement walks through the sample
array of state capitals and echoes a list:

$capitals = array(“CA” => “Sacramento”, “TX” => “Austin”,“OR” => “Salem” );
ksort($capitals);

foreach( $capitals as $state => $city )
{
   echo “$city, $state”;
}


On two dimensional array...


echo “”;
 foreach( $productPrices as $category )
{
   foreach( $category as $product => $price )
  {
       $f_price = sprintf(“%01.2f”, $price);
       echo “”;
   }
}
echo “<table border="1"><tbody><tr><td>$product:</td> <td>\$$f_price</td></tr></tbody></table>”;

No comments:

Post a Comment