Alex Rivera | Logout

How can I loop through an associative array and get the key?

Asked 2009-12-23T09:41:55.573
219

My associative array:

$arr = array(
   1 => "Value1",
   2 => "Value2",
   10 => "Value10"
);

Using the following code, $v is filled with $arr's values

 foreach ($arr as $v){
    echo $v;    // Value1, Value2, Value10
 }

How do I get $arr's keys instead?

 foreach (.....){
    echo $k;    // 1, 2, 10
 }
Edit
Report

1 Answer

5

The following will allow you to get at both the key and value at the same time.

foreach ($arr as $key => $value)
{
  echo($key);
}
answered 2009-12-23T09:44:42.180

Your Answer