27

In PHP, I have an associative array like this

$a = array('who' => 'one', 'are' => 'two', 'you' => 'three');

How to write a foreach loop that goes through the array and access the array key and value so that I can manipulate them (in other words, I would be able to get who and one assigned to two variables $key and $value?

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
Tu Hoang
  • 4,622
  • 13
  • 35
  • 48
  • 5
    It is described in the documentation: http://php.net/manual/en/control-structures.foreach.php. – Felix Kling Jun 21 '11 at 16:58
  • 1
    possible duplicate of [PHP - How to loop through a associative array and get the key name?](http://stackoverflow.com/questions/1951690/php-how-to-loop-through-a-associative-array-and-get-the-key-name) – Felix Kling Jun 21 '11 at 17:02

2 Answers2

53
foreach ($array as $key => $value) {
    echo "Key: $key; Value: $value\n";
}
Thiago Silveira
  • 5,033
  • 4
  • 26
  • 29
8

@Thiago already mentions the way to access the key and the corresponding value. This is of course the correct and preferred solution.

However, because you say

so I can manipulate them

I want to suggest two other approaches

  1. If you only want to manipulate the value, access it as reference

    foreach ($array as $key => &$value) {
      $value = 'some new value';
    }
    
  2. If you want to manipulate both the key and the value, you should going an other way

    foreach (array_keys($array) as $key) {
      $value = $array[$key];
      unset($array[$key]); // remove old key
      $array['new key'] = $value; // set value into new key
    }
    
KingCrunch
  • 128,817
  • 21
  • 151
  • 173