Bug #54408 [Com]: Unexpected behaviour when using by-reference iteration

From: Date: Tue, 26 Apr 2011 06:33:23 +0000
Subject: Bug #54408 [Com]: Unexpected behaviour when using by-reference iteration
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-160373@lists.php.net to get a copy of this message
Edit report at http://bugs.php.net/bug.php?id=54408&edit=1

 ID:                 54408
 Comment by:         blacknot at gmail dot com
 Reported by:        hitchiker at mail dot ru
 Summary:            Unexpected behaviour when using by-reference
                     iteration
 Status:             Open
 Type:               Bug
 Package:            Arrays related
 Operating System:   Win 7 x64, 2.6.18
 PHP Version:        5.3.6
 Block user comment: N
 Private report:     N

 New Comment:

I have similar problem:

$tags = array('iphone', 'apple', 'iPhone 4');
foreach ($tags as &$v) $v = trim($v);
           
$tags2 = $tags;
foreach ($tags2 as &$a) $a = '*';
           
print_r($tags);

Result:
Array
(
   [0] => iphone
   [1] => apple
   [2] => *
)


Previous Comments:
------------------------------------------------------------------------
[2011-04-08 13:10:27] hitchiker at mail dot ru

I was sure that arrays are passed to functions by value, not by
reference. It looks like by-reference iteration changes array not only
isnide foreach statement, but array remains changed even after
iteration.

------------------------------------------------------------------------
[2011-03-28 14:35:20] hitchiker at mail dot ru

Description:
------------
I was sure that arrays are passed to functions by value, not by
reference. It looks like after by-reference iteration changes array not
only isnide foreach statement, but array remains changed even after
iteration.

Test script:
---------------
<?php
$a = array(1,2,3,4);

function myf($a,$k){
    $a[$k] = 9;
}
foreach ($a as $k => &$v) {
    myf($a, $k);
}
//myf($a, 3);
var_dump($a);
die();

Expected result:
----------------
array
  0 => int 1
  1 => int 2
  2 => int 3  
  3 => int 4

Actual result:
--------------
array
  0 => int 9
  1 => int 9
  2 => int 9
  3 => &int 9


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



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


Thread (11 messages)

« previous php.bugs (#160373) next »