views:

74

answers:

2

hi guys,

I am confused from 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/>';
}
+3  A: 

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/>';
}
codaddict
yeah it worked n helped but u missed to state why it happens
KoolKabin
+1  A: 

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

ramblex
thnx. your second link exactly points to my solution.
KoolKabin
@ramblex, for the casual/curious reader (and because links do break over time), what's the solution say, basically?
Yar