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
If you only want to manipulate the value, access it as reference
foreach ($array as $key => &$value) { $value = 'some new value'; }
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 }
精彩评论