one more thing - could someone explain to me the use of this foreach loop that goes through this array...
the array:
Code: Select all
$prices['Tires'] = 100;
$prices['Oil'] = 10;
$prices['Spark Plugs'] = 4;
the loop:
Code: Select all
foreach ($prices as $key => $value)
echo $key.'=>'.$value.'<br />';
I understand that the array will pretty much be this: $prices = array ('Tires', 'Oil', 'Spark Plugs'); Except that each item will have the above price attached to it. However - I don't understand how the foreach loop will grab not only the keys (tires, oil, spark plugs) - but also the values attached to them (100, 10, 4). I will also add that I understand how a foreach loop is supposed to work - in that it takes the first key and stores that in a variable which in this case is $key, executes a statement - and then stores the next key in the variable - but what is the significance of adding '=> $value' to the end of the loop? H ow does that display the Price attached to the items in the array? Maybe it's all the new terminology - but I think after writing out my question I am getting a little closer to understanding how this works.
Bear with me!
By using an associative array - the element I enter becomes the key... and therefore the variable I attach to it becomes it's value... correct? So the foreach loop would actually output the array element - and it's contents. Right?
(did I just figure that out by myself?

)
EDIT: For my sake of completeness I'll try to explain to myself how to use the each(); function to access the same values. You guys need to tell me if I'm on the right track.
Code: Select all
while( $element = each( $prices) )
{
echo $element[ 'key' ];
echo ' - ';
echo $element[ 'value'];
echo '<br />';
}
It is my understanding that the each() function will take the first key element in the array (which is tires) - and stores it into the variable $element, along with it's value. The block of code inside the while loop will then neatly output the element 'Tires' and it's value - which would be 100. The loop will then go through the rest of the array until the end is reached. Correct?
If I am correct, and I did actually figure this out for myself - what confused me was that I didn't realize that the array element holds a value - and that the array element is not the value itself. Damn you associative arrays, and your confusing - but useful features!
DOUBLE EDIT: Using the list() function is next in my book - so I may be back!