Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

$key=>$value -- are the words "key" and "value" arbitrar

Status
Not open for further replies.

djbeta

IS-IT--Management
Apr 16, 2004
46
US

In the book I'm reading, the author said that the words $key and $value are arbitrary... but I'm not sure I see how that's possible..

here's the example in the book--------------

// Create the array.
$movies = array (
'10' => 'Casablanca',
'9.65' => 'To Kill a Mockingbird',
'2.35' => 'The English Patient',
'8' => 'Traffic');

// Display the movies sorted by title:
echo 'Sorted by title:<br /><pre>Rating Title
';
asort($movies);
foreach ($movies as $key => $value) {
echo "$key\t$value\n";
}
echo '</pre>';

would it be the same with "$duck" and "$goose" ??--------

// Create the array.
$movies = array (
'10' => 'Casablanca',
'9.65' => 'To Kill a Mockingbird',
'2.35' => 'The English Patient',
'8' => 'Traffic');

// Display the movies sorted by title:
echo 'Sorted by title:<br /><pre>Rating Title
';
asort($movies);
foreach ($movies as $duck => $goose) {
echo "$duck\t$goose\n";
}
echo '</pre>';
------------------------

if it's true that key and value don't have to be called key and value,
how would php know which is the duck and which is the goose ????


am i making any sense.. ??? :)



 
The names of the variables in the $key and $value positions in a foreach are completely arbitrary. PHP knows which is which from the "=>" operator between the $key and $value positions in the foreach statement. Notice this operator is the same one you used to assign values to your associative array.

Want the best answers? Ask the best questions!

TANSTAAFL!!
 

Thanks very much. I do get it now after your confirmation and more examples. I had in fact tried to find my answer from other sources (including the text I was quoting from the book that had in fact had plenty of errors in it-- so i was partially wondering about the author's use of the word "arbitrary" but didn't think about that until being led by you to think about the due diligence I had in fact done) I don't have a friend or associate who knows a thing about php. Next time I post I will try to display these facts if that will help. Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top