0

This is the relevant code:

foreach($familyNumbers as $questionNumber) {
    error_log($questionNumber);
    $questionNumber = substr($questionNumber, 1);
    error_log($questionNumber);
}
error_log(print_r($familyNumbers, true));

It's my understanding that the "as" variable when changed in the foreach loop should also modify the value in the array, however as my error logs show:

#10441
10441
#10442
10442
#10307
10307
#10602
10602
Array
(
    [0] => #10441
    [1] => #10442
    [2] => #10307
    [3] => #10602
)

I use foreach in other sections of my code and it works as expected, but here it does not. Should I just use a for loop for indices instead?

artie
  • 119
  • 7
  • 2
    If you want to modify the values inside the loop you need to pass by reference, by preceding the variable with an ampersand: `foreach($familyNumbers as &$questionNumber)` – Alex Howansky Oct 21 '21 at 20:12
  • 2
    Alternatively: `$familyNumbers = array_map(fn($v) => ltrim($v, '#'), $familyNumbers);` – Alex Howansky Oct 21 '21 at 20:14
  • 1
    Reference would be my pick but also modify original by key `foreach($familyNumbers as $key => $questionNumber) { $familyNumbers[$key] = substr($questionNumber, 1); ` – AbraCadaver Oct 21 '21 at 20:15
  • @AlexHowansky You are a gem, that was the issue. The next foreach loop though i use `foreach($family_groups as $indiv_group) {` and the line `$indiv_group = array_merge($indiv_group, $familyNumbers);` which correctly changes the nested array value, is that a type difference between string and array causing it? – artie Oct 21 '21 at 20:16

0 Answers0