Modify Array Values in Foreach Loop

PHP foreach change original array values

In PHP, passing by reference (&) is ... controversial. I recommend not using it unless you know why you need it and test the results.

I would recommend doing the following:

foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}

So basically use $field when you need the values, and $fields[$key] when you need to change the data.

Modify array values in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

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.

change values in array when doing foreach

The callback is passed the element, the index, and the array itself.

arr.forEach(function(part, index, theArray) {
theArray[index] = "hello world";
});

edit — as noted in a comment, the .forEach() function can take a second argument, which will be used as the value of this in each call to the callback:

arr.forEach(function(part, index) {
this[index] = "hello world";
}, arr); // use arr as this

That second example shows arr itself being set up as this in the callback.One might think that the array involved in the .forEach() call might be the default value of this, but for whatever reason it's not; this will be undefined if that second argument is not provided.

(Note: the above stuff about this does not apply if the callback is a => function, because this is never bound to anything when such functions are invoked.)

Also it's important to remember that there is a whole family of similar utilities provided on the Array prototype, and many questions pop up on Stackoverflow about one function or another such that the best solution is to simply pick a different tool. You've got:

  • forEach for doing a thing with or to every entry in an array;
  • filter for producing a new array containing only qualifying entries;
  • map for making a one-to-one new array by transforming an existing array;
  • some to check whether at least one element in an array fits some description;
  • every to check whether all entries in an array match a description;
  • find to look for a value in an array

and so on. MDN link

PHP foreach change array value

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

PHP changing array value in foreach

A foreach loop works by copying each value into a temporary variable.

If you want to edit the original array, you have two solutions :

Either pass the value with a reference, using & :

foreach ($items as &$item) {
/*...*/
$item['stock'] = $stock_quantity;
}

Or use the $key=>$value notation and edit the original array :

foreach ($items as $key => $item) {
/*...*/
$items[$key]['stock'] = $stock_quantity;
}

Changing a value inside the array in a forEach() loop

Suggestion : move newArray outside the clicked function as it is going to update on click.

Implementation : You can use Array.filter() method on newArray to check if record as per the input id is available or not and then by using Array.find() you can do filtering on the mainArray if there is no data in newArray.

Live demo :

const newArray = [];

function clicked(inp){
const mainArray = [
{ id: 1, name: "Shoes",stock: 5, price: 10 },
{ id: 2, name: "Bag",stock: 10, price: 50 },
];

const findInNewArr = newArray.filter(item => inp === item.id);

if (findInNewArr.length) {
newArray[0].stock += 1;
} else {
const findInMainArray = mainArray.find(element => inp === element.id);
if (findInMainArray) {
findInMainArray.stock = 1;
newArray.push(findInMainArray);
}
}

console.log(newArray);

}
<button id="1" onclick="clicked(2)">Click me</button>

Update array object in foreach loop with javascript

you need to use Array.reduce method: