A reference to an array that does not work in PHP

I got confused as a result of the following code: I cannot get the 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/>'; } 

Conclusion: 30, 40, 40

Expected: 30, 40, 50

But then again, if I do a little 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/>'; } 
+4
source share
2 answers
+1
source

You need to disable $DataRow after the loop in which you use 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 use another variable and avoid canceling ... although I would not recommend it, since $ DataRow still refers to the last element of the array, and any subsequent rewriting can 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/>'; } 
+3
source

Source: https://habr.com/ru/post/1309406/


All Articles