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 Link to comment https://forums.phpfreaks.com/topic/170235-setting-values-for-array-doesnt-work/ 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"; } Link to comment https://forums.phpfreaks.com/topic/170235-setting-values-for-array-doesnt-work/#findComment-897998 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); Link to comment https://forums.phpfreaks.com/topic/170235-setting-values-for-array-doesnt-work/#findComment-898000 Share on other sites More sharing options...
Bricktop Posted August 14, 2009 Share Posted August 14, 2009 Edit, above posts same as mine. Link to comment https://forums.phpfreaks.com/topic/170235-setting-values-for-array-doesnt-work/#findComment-898003 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!! :-) Link to comment https://forums.phpfreaks.com/topic/170235-setting-values-for-array-doesnt-work/#findComment-898007 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.