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?

2

2 Answers 2

54
foreach ($array as $key => $value) {
    echo "Key: $key; Value: $value\n";
}
Sign up to request clarification or add additional context in comments.

5 Comments

And how to format the output? Like I have $a['who'] = 10.99999, how to echo it out only as 10.99? (too demical digits)?
@TannerHoang: That is another question and already answered: stackoverflow.com/search?q=php+format+decimal
@Tanner: This feels like a completely other question. Have a look at sprintf() in the manual.
It is indeed another question. Anyway, you should use printf("%.2f", $value);
I actually used this one given Thiago foreach loop. echo $key.": ".number_format($value,2);
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
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.