Page 1 of 1

foreach, I don't get this one?

Posted: Sun May 25, 2003 5:20 am
by father
This is my array

Code: Select all

$pricesї'tires']=100;
 $pricesї'oil']=10;
 $pricesї'spark plugs']=4;
then I have the following foreach loop

Code: Select all

foreach ($prices as $key )
 	echo $key.'=>'.$value.'<br/>';

which produces the following result

100=>
10=>
4=>

If I add the $value variable

Code: Select all

foreach ($prices as $key => $value)
 	echo $key.'=>'.$value.'<br/>';
my result becomes

tires=>100
oil=>10
spark plugs=>4


I'm not specifying a variable of $value anywhere so does php understand this?
If it does then again why does $key become the value if I don't specify =>value as per the first set of code?

Posted: Sun May 25, 2003 5:48 am
by volka
that's how foreach() is designed.
It doesn't depend on the names of the variables but on the amount and structure you pass to foreach

Code: Select all

foreach ($prices as $ramalamadingdong => $maryHadALittleLamb)
   echo $ramalamadingdong, '=>', $maryHadALittleLamb, '<br/>';
;)


http://php.net/foreach