Reference to array not working as expected in PHP
I am confused fro开发者_JS百科m the result of the following code: I can't get my expected result:
$arrX = array('a'=>array('val'=>10),'b'=>array('val'=>20), 'c'=>array('val'=>30));
foreach( $arrX as &$DataRow )
{
$DataRow['val'] = $DataRow['val'] + 20;
}
foreach( $arrX as $DataRow )
{
echo '<br />val: '.$DataRow['val'].'<br/>';
}
Output: 30, 40, 40
Expected: 30, 40, 50
But again if i make small chage it works fine,
$arrX = array('a'=>array('val'=>10),'b'=>array('val'=>20), 'c'=>array('val'=>30));
foreach( $arrX as &$DataRow )
{
$DataRow['val'] = $DataRow['val'] + 20;
}
foreach( $arrX as &$DataRow )
{
echo '<br />val: '.$DataRow['val'].'<br/>';
}
You need to unset the $DataRow
after the loop in which you are making use of it as a reference:
$arrX=array('a'=>array('val'=>10),'b'=>array('val'=>20), 'c'=>array('val'=>30));
foreach( $arrX as &$DataRow ) {
$DataRow['val'] = $DataRow['val'] + 20;
}
// at this point $DataRow is the reference to the last element of the array.
// ensure that following writes to $DataRow will not modify the last array ele.
unset($DataRow);
foreach( $arrX as $DataRow ) {
echo '<br />val: '.$DataRow['val'].'<br/>';
}
You can make use of a different variable and avoid the unsetting..although I would not recommend it as $DataRow is still a reference to the last array element and any overwrite of it later on will cause problems.
$arrX=array('a'=>array('val'=>10),'b'=>array('val'=>20), 'c'=>array('val'=>30));
foreach( $arrX as &$DataRow ) {
$DataRow['val'] = $DataRow['val'] + 20;
}
foreach( $arrX as $foo) { // using a different variable.
echo '<br />val: '.$foo['val'].'<br/>';
}
Your question (almost exactly) is addressed on the php foreach manual page :)
http://www.php.net/manual/en/control-structures.foreach.php
http://www.php.net/manual/en/control-structures.foreach.php#92116
精彩评论