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

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.