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 :)

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

In addition, we can simply use "foreach ($array as &$value)", without need for $key. I hope this helps you too. Peace.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.