4

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/>';
}
2

2 Answers 2

3

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/>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

for the casual/curious reader (and because links do break over time), what's the solution say, basically?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.