a simple sample for loop and while loop in php

$prices = array(‘Tires’=>100, ‘Oil’=>10, ‘Spark Plugs’=>4);

The foreach loop has a slightly different structure when using associative arrays.You
can use it exactly as you did in the previous example, or you can incorporate the keys as
foreach ($prices as $key => $value) {
echo $key.” – “.$value.”<br />”;

The following code lists the contents of the $prices array using the each() construct:
while ($element = each($prices)) {
echo $element[‘key’];
echo ” – “;
echo $element[‘value’];
echo “<br />”;

There is a more elegant and more common way of doing the same thing.The construct
list() can be used to split an array into a number of values.You can separate two
of the values that the each() function gives you like this:
while (list($product, $price) = each($prices)) {
echo “$product – $price<br />”;

The output of this script fragment is shown in Figure 3.2.

Tires – 100
Oil – 10
Spark Plugs – 4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s