1

I must be missing something about how PHP arrays are handled. When I execute the following code:

<?php
$ary = array(
  "alpha" => array("A"=>1,"B"=>2,"C"=>3),
  "beta" => array("A"=>7,"B"=>8,"C"=>9)
  );

foreach ($ary as $key => $vals) {
  $vals["B"]=99;
  echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>

I get:

alpha= 1 99 3
beta= 7 99 9
2

The change to 99 in each case seems to be lost. What am I doing wrong?

2
  • 1
    foreach ($ary as $key => &$vals) Commented Sep 3, 2016 at 20:34
  • Thank you! I did not realize that foreach was pass by value by default. Makes a lot of sense now. Commented Sep 4, 2016 at 11:13

2 Answers 2

1

If you want to change items of array in foreach statement you should pass by reference.

foreach ($ary as $key => &$vals) {
}
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$ary = array(
  "alpha" => array("A"=>1,"B"=>2,"C"=>3),
  "beta" => array("A"=>7,"B"=>8,"C"=>9)
  );

foreach ($ary as $key => $vals) {
  //$vals["B"]= 99;
  $ary[$key]["B"] = 99;
  echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>

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.