Jump to content

Setting values for Array doesnt work


Dollops

Recommended Posts

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

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";
}

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);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.