2

Is there a way to set the value of members of an array with foreach?

<?
  $arr = array(0=>'a',1=>'b',2=>'c',3=>'d');

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

  var_dump($arr);
?>

returns:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
}

Where what I am trying to get it to return is:

   array(4) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "a"
      [2]=>
      string(1) "a"
      [3]=>
      string(1) "a"
    }

Here is a link to the codepad I was using.

http://codepad.org/FQpPYFtz

1
  • +1 for providing a complete, minimal and usefully abstracted sample. More people should do it this way. Commented Feb 19, 2012 at 11:04

2 Answers 2

3
$arr = array(0=>'a',1=>'b',2=>'c',3=>'d');

foreach($arr as $key => &$value) {  // <-- use reference to $value
  $value = 'a';
}

var_dump($arr);
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly the quick fix I was searching for. Looks like I am going to have to try harder to understand this reference thing. Thank you for pointing this out to me!
3

It is quite simple:

foreach ($data as $key => $value) {
    $data[$key] = 'new value';
}

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.