Dollops Posted August 14, 2009 Share Posted August 14, 2009 My code is as below, $totalsx = array( array('days'=> "1", 'total' => "X"), array('days'=> "2", 'total' => "X"), array('days'=> "3", 'total' => "X"), array('days'=> "4", 'total' => "X"), array('days'=> "5", 'total' => "X"), array('days'=> "6", 'total' => "X"), array('days'=> "7", 'total' => "X"), ); foreach ($totalsx as $key =>$totals ){ $totals ['total'] = "Changed value"; } print_r ($totalsx ); When $totalsx prints, the value for 'total' hasnt changed to "Changed Value" - Any ideas why? Chheers Quote Link to comment Share on other sites More sharing options...
aschk Posted August 14, 2009 Share Posted August 14, 2009 Yes, because each time you iterate over $totalsx you're getting a copy of $totals, which you are then editing. You're not getting a reference to the internal $totalsx item. Thus you have 2 options. Set it via reference, or via full array path. Both are supplied below: By reference <?php foreach ($totalsx as $key =>&$totals ){ $totals['total'] = "Changed value"; } <?php foreach ($totalsx as $key =>$totals ){ $totalsx[$key]['total'] = "Changed value"; } Quote Link to comment Share on other sites More sharing options...
Mark Baker Posted August 14, 2009 Share Posted August 14, 2009 It won't change, because $totals is a copy of the array entry, not the array entry itself Either foreach ($totalsx as $key =>$totals ){ $totalsx[$key]['total'] = "Changed value"; } or foreach ($totalsx as &$totals ){ $totals['total'] = "Changed value"; } unset($totals); Quote Link to comment Share on other sites More sharing options...
Bricktop Posted August 14, 2009 Share Posted August 14, 2009 Edit, above posts same as mine. Quote Link to comment Share on other sites More sharing options...
Dollops Posted August 14, 2009 Author Share Posted August 14, 2009 Awesome guys, I'll give this a go!! :-) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.