views:

251

answers:

9

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
 }
+6  A: 

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);
}
Trevor Johns
Assuming you use the result from array_keys() in the 2nd example your foreach will only echo the indexes and not the values of array_keys()
Htbaa
Good catch. That's a copy and paste error. Fixed. :)
Trevor Johns
A: 

Have a look at this other post:

http://stackoverflow.com/questions/1219548/java-and-python-equivalent-of-phps-foreacharray-as-key-value

ruibm
Hum, what's up with the -1? The answer was in that post and it actually explains how to do it in other programming languages.
ruibm
A: 

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

foreach ($arr as $key => $value)
{
  echo($key);
}
Jeff Beck
+2  A: 
foreach($array as $k => $v)

Where $k is the key and $v is the value

Or if you just need the keys use array_keys()

Htbaa
+6  A: 

You can do:

foreach (array_expression as $key => $value) {
 echo $key;
}
codaddict
+1  A: 

PHP array keys Documentation is here

Rigobert Song
A: 
 foreach($arr as $key=>$value){
    echo($key);    // key
 }
Ngu Soon Hui
A: 

Oh I found it in the PHP manual.

foreach ($array as $key => $value){
    statement
}

The current element's key will be assigned to the variable $key on each loop.

Jenko
A: 

Use $key => $val to get the keys:

<?php

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

foreach ($arr as $key => $val) {
   print "$key\n";
}

?>
Raphink