null
null

Reputation: 1433

Is a foreach loop not able to handle references in PHP?

I've just noticed that you cannot deal with references in a foreach loop. Take this code example:

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


    foreach($arr as $a) {
        $foo[] = &$a;
    }

    var_dump($foo);

Surprisingly, the output is array(5) { [0]=> &int(5) [1]=> &int(5) [2]=> &int(5) [3]=> &int(5) [4]=> &int(5) }.

However, I expected a copy of $arr. I can only a

   for($i = 0; $i < count($arr); $i++) {
      $foo[] = &$arr[$i];
   }

   var_dump($foo);

Output: array(5) { [0]=> &int(1) [1]=> &int(2) [2]=> &int(3) [3]=> &int(4) [4]=> &int(5) }

Why is such behavior desirable?

Upvotes: 0

Views: 43

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

The temporary variable $a changes each iteration until it finally equals 5, so references to it are 5. This will give you the desired behaviour:

foreach($arr as &$a) {
    $foo[] = &$a;
}

This will reference $a to the actual array values.

Upvotes: 2

Related Questions