2

Let's say I got following code:

$arr = array("1" => 1, "2" => 2, "3" => 3, "4" => "4", "5" => "5");
foreach($arr as $key => $value) {
    echo "Array[".$key."]: " . $arr[$key] . "<br>";
    echo "Value: " . $value . "<br>";
    if (isset($arr[$key+1])) $arr[$key+1] = $arr[$key+1]*2;
}

which creates this output:

Array[1]: 1
Value: 1
Array[2]: 4
Value: 2
Array[3]: 6
Value: 3
Array[4]: 8
Value: 4
Array[5]: 10
Value: 5

Now my question is, why does $value differ from $arr[$key] while iterating through said array? Is $value not getting updated with the array because foreach is just handling a copy of the array or something? Can I solve this issue without using $arr[$key] inside of the loop?

StrikeAgainst
  • 556
  • 6
  • 23

3 Answers3

0

As far as i know PHP uses "copy on write", so everything is a reference until you try to write to it, at that time a copy is made where you will write to.

So yes, that means your value for the array you are iterating over is different than the set-by-index value.

Also see:

How does PHP 'foreach' actually work?

Community
  • 1
  • 1
Ronald Swets
  • 1,669
  • 10
  • 16
0

I have the answer for what happens but not why it happens.

value are *2 when index are in series

if array is (1=>1,2=>2)
than o/p is in $arr[$key](for each) 1 value 1,2 value 4

if array is (3=>1,2=>2)
than o/p is in $arr[$key](for each) 3 value 1,2 value 2

if array is (2=>1,3=>2)
than o/p is in $arr[$key](for each) 2 value 1,3 value 4


if array is (1=>5,3=>2,4=>'3',6=>8)
than o/p is in $arr[$key](for each) 1 value 5,3 value 2,4 value 6,6 value 8
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40
Parth Chavda
  • 1,819
  • 1
  • 23
  • 30
0

foreach($arr as $key => $value) { $value=$arr[$key]; echo "Array[".$key."]: " . $arr[$key] . "<br>"; echo "Value: " . $value . "<br>"; if (isset($arr[$key+1])) $arr[$key+1] = $arr[$key+1]*2; }

i think you should assign manually $value=$arr[$key]; in for loop ,for getting output you want.

In foreach, PHP iterates over a copy of the array instead of the actual array. In contrast, when using each( ) and for, PHP iterates over the original array. So, if you modify the array inside the loop, you may (or may not) get the behavior you expect.

Bijal
  • 132
  • 1
  • 8