skip to Main Content

This is my code:

$arr = [
  
    [step_1] => Array
        (
            [method] => getLastRealisesData
            [description] => Get last realises data
            [error] => null
            [done] => 0
        )

    [step_2] => Array
        (
            [method] => downloadFile
            [description] => Download file
            [error] => null
            [done] => 0
        )

];

foreach($arr as $item){
   $result = 0;
   if($result == 0){
      $item['done'] = 0;
      $item['error'] = 'Error message';
      break;
   }

   $result = 1;
}

My value did not update, why?
I need to update my value if I my result == 0
Mayby I need to use object or somethink else…

2

Answers


  1. If you want to amend the array you are processing with the foreach loop, you have to use a reference, otherwise the foreach gets a copy of the array to process and any changes made within the loop to the array will dissapear at the end of the foreach as the copy is discarded.

    
    foreach($arr as &$item){
    //  note        ^ reference
        $result = 0;
        if($result == 0){
            $item['done'] = 0;
            $item['error'] = 'Error message';
            break;
        }
        $result = 1;
    }
    unset($item);  // unset the reference
    
    
    Login or Signup to reply.
  2. From php documentation here:

    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.

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    // $arr is now array(2, 4, 6, 8)
    unset($value); // break the reference with the last element
    ?>
    

    Also you may be interested in what by reference means. Again, docs.

    Note also that reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search