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


Question

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
 }
1
158
8/11/2014 5:37:47 AM

Accepted Answer

You can do:

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

As described in PHP docs.

307
9/4/2017 7:07:15 AM

If you use array_keys(), PHP will give you an array filled with just the keys:

$keys = array_keys($arr);
foreach($keys as $key) {
    echo($key);
}

Alternatively, you can do this:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon