How to loop through an associative array and get the key?

Robin Rodricks picture Robin Rodricks · Dec 23, 2009 · Viewed 314.6k times · Source

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
 }

Answer

codaddict picture codaddict · Dec 23, 2009

You can do:

foreach ($arr as $key => $value) {
 echo $key;
}

As described in PHP docs.