2

I have following code as below,

 <?php
    $a = [1,2,3];
    foreach($a as &$val) {
        $val = $val + 1;
    }

    foreach($a as $val) {
        $val = $val - 1;
    }

    var_dump($a);

    // output 2,3,1
?>

I got output 2,3,1 as final array instead of 2,3,4 and i can't understand how php is interpreting this code, Can anyone help me to understand how the things is going here?

4
  • 1
    @AlonEitan No, the first pass-by-reference should create 2,3,4 and be unaffected by the seconded foreach. Commented May 12, 2018 at 17:48
  • @BenM Oh, missed that. Thanks for letting me know Commented May 12, 2018 at 17:49
  • 1
    Accessing the loop variable of foreach by reference means searching for trouble. Don't do it! Commented May 12, 2018 at 20:09
  • 1
    The answer to your question is explained in the documentation of foreach in a big red warning box. Commented May 12, 2018 at 20:11

1 Answer 1

5

You need to call unset() on the reference in your first foreach() to get the expected behaviour:

$a = [1, 2, 3];

foreach($a as &$val) 
{
    $val = $val + 1;
}

unset($val);

// $a = [2, 3, 4];

See the note in the documentation for this:

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

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

6 Comments

I think question is about why output is [2,3,1] instead of [2,3,4]
without an unset($value), $value is still a reference to the last item: $arr[3]. It's in the docs, guys.
unset() should be called after foreach, not inside of it.
@rob006 It's actually irrelevant in this instance: eval.in/1006699
@BenM result may be the same, but it does not make any sense to put it inside of foreach, it only adds unnecessary overhead.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.