开发者

PHP: Printing Associative Array

开发者 https://www.devze.com 2023-03-14 06:28 出处:网络
In PHP, I have an associative array like this $a = array(\'who\' => \'one\', \'are\' => \'two\', \'you\' => \'three\');

In PHP, I have an associative array like this

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

How to write a foreach loop 开发者_JAVA技巧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?


foreach ($array as $key => $value) {
    echo "Key: $key; Value: $value\n";
}


@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
    }
    
0

精彩评论

暂无评论...
验证码 换一张
取 消