Advertisement
Advertisement


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

Accepted Answer

You can do:

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

As described in PHP docs.

2017/09/04
340
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);
}
2009/12/23

Nobody answered with regular for loop? Sometimes I find it more readable and prefer for over foreach
So here it is:

$array = array('key1' => 'value1', 'key2' => 'value2'); 

$keys = array_keys($array);

for($i=0; $i < count($keys); ++$i) {
    echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}

/*
  prints:
  key1 value1
  key2 value2
*/
2016/10/19

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()

2009/12/23

I use the following loop to get the key and value from an associative array

foreach ($array as $key => $value)
{
  echo "<p>$key = $value</p>";
}
2015/08/26

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

foreach ($arr as $key => $value)
{
  echo($key);
}
2009/12/23

Source: https://stackoverflow.com/questions/1951690
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]