Lelio Faieta
Lelio Faieta

Reputation: 6684

update array with a value coming from the same array

I have an array with this structure (this is one of the entries):

[11] => Array
        (
            [id_cred] => CD000000905
            [gbv_tot] => 482197.51
            [ammesso] => 482197.51
            [tipo] => 1
            [importo] => 0
            [stato] => aperta
        )

I loop through it in a foreach to set [importo] to be equal to [gbv_tot] or [ammesso] based on some conditions. I wrote this code but seems not to update the value of the key [importo].

foreach($creds as $cred){
    if(($cred['tipo'] == '1')&&($tipo_az == 'conc')){
        //sto elaborando un chirografo in una azione concorsuale quindi prendo il nominale
        if($cred['stato']=='aperta'){
            $gbv_compl = $gbv_compl + $cred['ammesso'];
            $cred['importo'] = $cred['ammesso'];
        }else{
            $cred['importo'] = 0;
        }
    }else{
        //sto elaborando qualcosa d'altro e quindi prendo il GBV
        if($cred['stato']=='aperta'){
            $gbv_compl = $gbv_compl + $cred['gbv_tot'];                 
            $cred['importo'] = $cred['gbv_tot'];
        }else{
            $cred['importo'] = 0;
        }
    }
}

I think this is not the right way to do it since I cannot get [importo] to be updated. What am I missing?

Upvotes: 1

Views: 111

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

With foreach($creds as $cred){ $cred will not refer to the main array. For each iteration it will assign the current element to $cred. You need to use the key -

foreach($creds as $key => $cred){

And set the value like -

$creds[$key]['importo'] = 'whatever value it is';

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

foreach ($creds as &$cred) {

By using the reference you can directly update them. Now -

$cred['importo'] = 0;

Will change the value of the current element of the main array.

Upvotes: 3

viral
viral

Reputation: 3743

Change this line,

foreach($creds as $cred){

to

foreach($creds as &$cred){ // pass $cres 's value by reference

Now, changes to $cred are applied to your array

Upvotes: 5

Related Questions