0

In my project I increase values of firstArray +3.After I increase values of secondArray +7 .

   $firstArray = array(
      'a' => 1,
      'b' => 3,
      'c' => 5,
   );

foreach ($firstArray as &$item) {
    $item += 3;
}
print_r($firstArray);

Result: Array ( [a] => 4 [b] => 6 [c] => 8)

  $secondArray = array(
    'a' => 11,
    'b' => 13,
    'c' => 17,
);

foreach ($secondArray as $key=>$item) {
    $secondArray[$key] += 7;
}

print_r($secondArray);

Result: Array ( [a] => 18 [b] => 20 [c] => 24 )

But problem is when I did print_r($firstArray) again; I have this result: Array ( [a] => 4 [b] => 6 [c] => 17 )

Why there is the difference in result fisrt and thisrd?

4
  • Where you get Result: Array ( [a] => 12 [b] => 22 [c] => 32 ) from? Commented Jan 11, 2014 at 10:51
  • this all code in one php page, this all 2 loops Commented Jan 11, 2014 at 10:52
  • Edited. I pasted firrst wrong resulr, sorry. Commented Jan 11, 2014 at 10:57
  • Because you're looping with a reference (&) in the first loop, you need to unset($item) immediately after that loop otherwise it's still a reference to the last entry in $firstArray... looping by reference should always be approached with caution Commented Jan 11, 2014 at 11:02

2 Answers 2

1

The problem is, that you used $item as a link, and after one loop you used it again(I think after reuse $item some of value were rewritten ). You need to unset($item) after first loop, and even alwas unset link after used them.

$firstArray = array(
    'a' => 1,
    'b' => 3,
    'c' => 5,
);

foreach ($firstArray as &$item) {
    $item += 3;
}
print_r($firstArray);

unset($item);

Now result is good

Sign up to request clarification or add additional context in comments.

Comments

1

You could use array_map instead of loops and pass-by-reference. You avoid mutation this way. For example:

$add = function($x) {
  return function($y) use($x) {
    return $x + $y;
  };
};

$firstArray = array_map($add(3), $firstArray);
$secondArray = array_map($add(7), $secondArray);

2 Comments

Yes, but it is not the answer on my question
The other answer has the solution to your particular issue; this is an alternative solution.

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.