1

I have a multidimensional associative array and im using two foreach to iterate them, i need to change a value from the original array, here a representation of my code and what ive tried:

$array = [
  ['id' => 1, 'customers' => [['customerName' => 'Daniel', 'age' => 20, 'isYoung' => false], ['customerName' => 'Patrick', 'age' => 56, 'isYoung' => false]]],
  ['id' => 4, 'customers' => [['customerName' => 'Paul', 'age' => 41, 'isYoung' => false]]]
];

foreach($array as $key => $value) {
  foreach($value['customers'] as $sKey => $sValue {
    if($sValue['age'] < 35) {
      $array[$key]['customers'][$sKey]['isYoung'] = true; //Doesnt Work
      $value['customers'][$sKey]['isYoung'] = true; //Doesnt Work
    }
  }
}

Any leads?

DSB
  • 597
  • 2
  • 6
  • 11

1 Answers1

1

The first assignment works for me. But you can simplify it by using reference variables for the iteration variables.

foreach($array as &$value) {
  foreach($value['customers'] as &$sValue) {
    if($sValue['age'] < 35) {
      $sValue['isYoung'] = true;
    }
  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, just realized that the problem was that after modifying the value I was pushing to an array $sValue and that caused the ‘isYoung’ attribute to be not modified – DSB Sep 01 '20 at 06:04
  • 1
    Without `&`, the iteration variables are copies, not references to the original array. – Barmar Sep 01 '20 at 06:05