Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you loop an associative array?

The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.

How do you print the key in an associative array?

Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.

Can we use for loop for associative array?

So as we can see in the example above, we can easily loop through indexed array using for loop. But for Associative Arrays we need to use ForEach loop.


You can do:

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

As described in PHP docs.


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

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

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


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

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

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