RSS

Foreach Loop

Sat, Jan 16, 2010

PHP & MySql

Note: This chapter requires you to have a basic knowledge of arrays. If you don’t know what arrays are or how they work, please first have a look at the arrays tutorial.

The foreach loop is used to get all keys and values from all indexes (’sub-variables’) of an array and handle them with your given (‘act’) code all one for one. A foreach loop looks like this (structure):

foreach ( $array as $key => $value ) {

    ... act code ...

}

The $array variable can be any array variable you want to handle and you can choose any variable name for $key and $value. In these variables ($key and $value in this example) the name ($key) and value ($value) of each index (‘sub-variable’) of the array will be stored and the act code will be ran. Example:

$product_prices = array("tv" => 599.95,
              "computer" => 899.95,
              "notebook" => 999.999
              );

foreach($product_prices as $prod => $price) {

    echo "Product: ".$prod." \n";
    echo "Price: ".$price." <p>";

}

Here we got an array with 3 indexes which indicate products (the name of the products are the
‘keys’ of the array) with their prices (the ‘values’ of the array). So I changed the variables $key and $value to the names $prod (product) and $price, which are in this case giving a better indication of what actually is stored into them. The output of this script is a list of the products and prices:

Product: tv
Price: 599.95

Product: computer
Price: 899.95

Product: notebook
Price: 999.999

Cheers,
Admin.