7

When you have a foreach loop like below, I know that you can change the current element of the array through $array[$key], but is there also a way to just change it through $value?

foreach($array as $key => $value){

}

It's probably really simple, but I'm quite new to PHP so please don't be annoyed by my question :)

fckye
  • 85
  • 1
  • 6

2 Answers2

13

To be able to directly assign values to $value, you want to reference $value by preceding it with & like this:

foreach($array as $key => &$value){
    $value = 12321; //the same as $array[$key] = 12321;
}

unset($value);

After the foreach loop, you should do unset($value) because you're still able to access it after the loop.
Note: You can only pass $value by reference when the array is a variable. The following example won't work:

foreach(array(1, 2, 3) as $key => &$value){
    $value = 12321; //the same as $array[$key] = 12321
}

unset($value);


The php manual on foreach loops

Jonan
  • 2,485
  • 3
  • 24
  • 42
0

there's a function for that, and is builtin since early version of PHP, is called array_map

commadelimited
  • 5,656
  • 6
  • 41
  • 77
ROLO
  • 581
  • 4
  • 13