I am writing PHP code to do some conversion of each value in an array and then add some values ββto the array from an external source (MySQL cursor or, say, another array). If I use foreach and a link to convert 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); ?>
( Here it is in PHPfiddle )
what data is damaged. Therefore i get
Array ( [0]=>A [1]=>B [2]=> [3]=>D [4]=>E [5] =>F )
instead
Array ( [0]=>A [1]=>B [2]=>C [3]=>D [4]=>E [5] =>F )
When I do not use the link and write
foreach( $data as &$x ) $x = strtoupper($x);
the conversion does not occur, of course, but the data is also not corrupted, 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, copying data solves the problem. But I would like to understand that there is a strange problem with this link and how to avoid such problems. Maybe it's generally bad to use PHP links in your code (for example, many talk about C pointers)?