How to loop through an associative array and get the key? [duplicate]
Solution 1:
You can do:
foreach ($arr as $key => $value) {
echo $key;
}
As described in PHP docs.
Solution 2:
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);
}
Solution 3:
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
*/
Solution 4:
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()
Solution 5:
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>";
}