Edit report at http://bugs.php.net/bug.php?id=53870&edit=1

 ID:                 53870
 Comment by:         uldericofilho at gmail dot com
 Reported by:        lolbummer at gmail dot com
 Summary:            Problem with passing array elements as references in
                     foreach
 Status:             Open
 Type:               Bug
 Package:            Arrays related
 Operating System:   Mac OS X Snow Leopard
 PHP Version:        5.3.5
 Block user comment: N
 Private report:     N

 New Comment:

On PHP 5.3.5 on CentOS 5.5 - same result. Proof of concept below:



echo "Result\n";

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

foreach($arr as &$a){

        $a*=2;

}

foreach($arr as $a){

        echo $a."\n";

}



echo str_repeat('-', 10)."\nExpected\n";



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

$arr = array_map(function($v){

        return $v*2;

}, $arr);

foreach($arr as $a){

        echo $a."\n";

}


Previous Comments:
------------------------------------------------------------------------
[2011-01-28 18:15:45] lolbummer at gmail dot com

Description:
------------
I created an array of strings that would be typecast to integers, and
cast them using a foreach loop, passing each element by reference. 
After dumping the resulting array, it gave (somewhat) expected results,
though after dumping each element individually, it gave an unexpected
result on the last element.

This happened with PHP 5.3.5 on Mac OS X Snow Leopard, but did not
happen on a Debian system with PHP 5.2.6.

Test script:
---------------
<?php

$array = array('1', '2', '5324', '435', '51');

foreach($array as &$element){

    $element = (int)$element;

}

var_dump($array);



foreach($array as $key => $element){

    var_dump($key);

    var_dump($element);

    echo "\n";

}

?>

Expected result:
----------------
array(6) {

  [0]=>

  int(1)

  [1]=>

  int(2)

  [2]=>

  int(3)

  [3]=>

  int(5324)

  [4]=>

  int(435)

  [5]=>

  int(51)

}

int(0)

int(1)



int(1)

int(2)



int(2)

int(3)



int(3)

int(5324)



int(4)

int(435)



int(5)

int(51)



Actual result:
--------------
array(6) {

  [0]=>

  int(1)

  [1]=>

  int(2)

  [2]=>

  int(3)

  [3]=>

  int(5324)

  [4]=>

  int(435)

  [5]=>

  &int(51)

}

int(0)

int(1)



int(1)

int(2)



int(2)

int(3)



int(3)

int(5324)



int(4)

int(435)



int(5)

int(435)


------------------------------------------------------------------------



-- 
Edit this bug report at http://bugs.php.net/bug.php?id=53870&edit=1

Reply via email to