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:
const data =
[ { uniqueIdentifier: 'theme_test', version: '2011120800' }
, { uniqueIdentifier: 'theme_test', version: '3011120800' }
, { uniqueIdentifier: 'theme_test', version: '4011120800' }
]
const result = Object.values(data.reduce( (r,{uniqueIdentifier,version}) =>
{
r[uniqueIdentifier] ??= { uniqueIdentifier, version:[] }
r[uniqueIdentifier].version.push(version)
return r
},{}))
console.log(result)
Related Topics
How to Get Multiple Selected Values of Select Box in PHP
How to Rename Uploaded File Before Saving It into a Directory
How to Read a Large File Line by Line
How to Zip a Whole Folder Using PHP
How to Remove Duplicate Values from an Array in PHP
Parse Query String into an Array
How to Get Body of a Post in PHP
How to "Flatten" a Multi-Dimensional Array to Simple One in PHP
Jquery Validate Remote Method Usage to Check If Username Already Exists
How to Access This Object Property With an Illegal Name
PHP Function to Generate V4 Uuid
A Simple Program to Crud Node and Node Values of Xml File
MySQL Query to Get Column Names
Converting String to Date and Datetime
How to Make a Calculator in PHP
Preg_Match(): Compilation Failed: Invalid Range in Character Class At Offset