foreach, I don't get this one?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
father
Forum Newbie
Posts: 5
Joined: Fri May 23, 2003 10:15 pm
Location: Australia

foreach, I don't get this one?

Post 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?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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
Post Reply