:::: MENU ::::
Monthly Archives: August 2012

PHP foreach and passing by reference

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

foreach($arr as $v){
    $arr[] = 1;
    echo $v;
}

output: 123456

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

foreach($arr as &$v){
    $arr[] = 1;
    echo $v;
}

output: 1234561111111111111111111111111111111111111111111111…
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) in /Users/gradzinski/dev/playground/foreach.php on line 7

So within the foreach loop we are adding 1 to referenced array arr and this is why we are failing into infinite loop.

Below you can find PHP foreach manual explanation that may put some light in that behaviour.

Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won’t work:

<?php foreach (array(1, 2, 3, 4) as &$value) { $value = $value * 2; } ?>