1

I am at a beginners level. I was reading the Php.net manual and I found this example there about foreach loop. I have tried my best to understand why does the second to last value gets copied to the last value but still no clue. Please answer in detail.

<?php

$arr = array(1, 2, 3, 4);

foreach($arr as &$value) {
    $value = $value * 2;
}

// $arr is now array(2, 4, 6, 8)

// without an unset($value), $value is still a reference to the last item: $arr[3]

foreach($arr as $key => $value) {
    // $arr[3] will be updated with each value from $arr...
    echo "{$key} => {$value} ";
    print_r($arr);
}

// ...until ultimately the second-to-last value is copied onto the last value

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

1 Answers1

0

Sorry for my bad english but it's not my native language. It's because your second foreach doesn't reinitialize $value, so it's still a reference. If you var_dump your array you will see this :

array(4) {
  [0]=>   
  int(2)  
  [1]=>   
  int(4)  
  [2]=>   
  int(6)  
  [3]=>   
  &int(8) 
}

Your last value is a reference, so it will take the value of $value. 2 on the first iteration, 4 on the second... For the last, it's himself, which have a value of 6 at the last time.

WildSteak
  • 31
  • 4
  • So what you're trying to say is that on last iteration we get this output 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) because on third iteration when the key was $key = 2 we stored 6 on $arr[3]. so when the became $key = 3 it was pointing to the location where 6 was already stored..right? – Shaikh Mudassir Aug 22 '19 at 10:27