I am writing PHP code to make some transformations of every value in an array, then to add some values to the array from external source (MySQL cursor or, say, another array). If I use foreach
and a reference to transform array values
<?php
$data = array('a','b','c');
foreach( $data as &$x )
$x = strtoupper($x);
$extradata = array('d','e','f');
// actually it was MySQL cursor
while( list($i,$x) = each($extradata) ) {
$data[] = strtoupper($x);
}
print_r($data);
?>
than data is beeing corrupted. So I get
Array ( [0]=>A [1]=>B [2]=> [3]=>D [4]=>E [5] =>F )
instead of
Array ( [0]=>A [1]=>B [2]=>C [3]=>D [4]=>E [5] =>F )
When I use no reference and write
foreach( $data as &$x )
$x = strtoupper($x);
transformation does not occur, of course, but data is not corrupted too, so I get
Array ( [0]=>a [1]=>b [2]=>c [3]=>D [4]=>E [5] =>F )
If I write code like this
<?php
$result = array();
$data1 = array('a','b','c');
foreach( $data1 as $x )
$result[] = strtoupper($x);
$data2 = array('d','e','f');
// actually it was MySQL cursor
while( list($i,$x) = each($data2) ) {
$result[] = strtoupper($x);
}
print_r($result);
?>
everything works as expected.
Array ( [0]=>A [1]=>B [2]=>C [3]=>D [4]=>E [5] =>F )
Of course, I copying data solves the problem. But I would like to understand what is the strange trouble with that reference and how such troubles can be avoided. Maybe it is generally bad to use PHP references in code (like many people say about C-pointers)?