0

I was wondering if someone have had the same problem. My code first:

<?php

    $testArray = [
        ['name' => 'one', 'value' => 10],
        ['name' => 'two', 'value' => 15],
        ['name' => 'three', 'value' => 8]
    ];

    foreach ($testArray as &$testArrayRow) {
        $testArrayRow['value'] += 10;
        echo '<div>'.$testArrayRow['name'].' = '.$testArrayRow['value'].'</div>';
    }

    foreach ($testArray as $testArrayRow) {
        echo '<div>'.$testArrayRow['name'].' = '.$testArrayRow['value'].'</div>';
    }

?>

Output below:

one = 20 two = 25 three = 18 one = 20 two = 25 two = 25

While I expect this:

one = 20 two = 25 three = 18 one = 20 two = 25 three = 18

Anyone who can tell me what is happening?

Thanks in advance!

AndVla
  • 713
  • 2
  • 6
  • 18
  • 1
    because `$testArrayRow` still contains reference of previous variable where it left, try changing it to something else like `foreach ($testArray as $abc) {` correct output will be displayed – manjeet Jul 29 '15 at 10:37
  • @Rizier123 That's what I was seraching for but a quick search didn't help. – AndVla Jul 29 '15 at 10:39
  • 1
    you can verify that by reinitializing `$testArrayRow` to '', next loop will likely to throw error as third index did not exists. – manjeet Jul 29 '15 at 10:42

0 Answers0