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

ID : 20349

viewed : 36

Tags : phploopsassociative-arrayphp

Top 5 Answer for php - How to loop through an associative array and get the key?

vote vote

100

You can do:

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

As described in PHP docs.

vote vote

89

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); } 
vote vote

76

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 */ 
vote vote

62

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

vote vote

52

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>"; } 

Top 3 video Explaining php - How to loop through an associative array and get the key?

Related QUESTION?