Click to See Complete Forum and Search --> : Accessing Just Keys in Loops


askohen
07-11-2007, 04:31 PM
I need to loop through a number of associative arrays; however, there are points that I really just need keys--not the values.

For example, in this array:
$testArray = array('Dog'=>'Lassie','Cat'=>'Garfield');
I need to access 'Dog' and 'Cat'.

Obviously, I could do this:
foreach($testArray as $animal => $name){
//do something with $animal
}


Question 1) In this case is it inefficient to create the $name variable since I am not using it (at this point) anyway?

Question 2) If so, is there another way to access just the keys in a loop?

bokeh
07-11-2007, 05:20 PM
foreach(array_keys($testArray) as $animal)
{
//do something with $animal
}

askohen
07-12-2007, 09:40 AM
Thanks! Worked like a charm. So aside from less typing I assume this is more efficient since the interpreter does not need to remember another variable, correct?