change initial array inside the foreach loop?
I don't think this is possible with a foreach
loop, at least the way you wrote it : doesn't seem to just be the way foreach
works ; quoting the manual page of foreach
:
Note: Unless the array is referenced, foreach operates on a copy
of the specified array and not the
array itself.
Edit : after thinking a bit about that note, it is actually possible, and here's the solution :
The note says "Unless the array is referenced" ; which means this portion of code should work :
$i = 0;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
}
Note the &
before $value
.
And it actually displays :
red
blue
white
white
white
white
Which means adding that &
is actually the solution you were looking for, to modify the array from inside the foreach
loop ;-)
Edit : and here is the solution I proposed before thinking about that note :
You could do that using a while
loop, doing a bit more work "by hand" ; for instance :
$i = 0;
$array = array('red', 'blue');
$value = reset($array);
while ($value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
$value = next($array);
}
Will get you this output :
red
blue
white
white
white
white
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>
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.
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
How to make array inside in foreach loop - php?
I suppose you're looking for this:
$input = array("teamA","teamB","teamC");
$data = [];
foreach($input as $value){
$assign = "50"; /* The data just temp */
$data[$value] = $assign;
}
echo $data["teamA"];
If $assign
is same for all keys:
$data = array_fill_keys($input, 50);
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.
Modify next element in array during foreach() loop
foreach loops through an array by taking a copy of the array and not by reference. You need to loop through the array by reference using the ampersand &
on the array value.
foreach($arr as $k => &$v) {
echo "<br> The ".$v['type'].' fruit is '.$v['color'];
// change the color of the next fruit?
if($v['type'] == 'banana') { $arr[$k+1]['color'] = 'green'; }
}
Why is my forEach loop not editing my array?
The forEach
method of an array does not modify the array, it just iterates over it. When you change the argument in the callback function, that doesn't affect the array either. Also, forEach
doesn't do anything with the return values from the callback. Once you calculate the value you want to use to replace, you can set it using the index and array arguments, like so.
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4, 19, 300, 3775, 299, 36, 209, 148, 169, 299, 6, 109, 20, 58, 139, 59, 3, 1, 139];
test.forEach(function(element, index, array){ if (element % 3 === 0){ element += 100; array[index] = element; }});
console.log(test);
Related Topics
HTML Form PHP Post to Self to Validate or Submit to New Page
How Download Big File Using PHP (Low Memory Usage)
PHP Spl_Autoload_Register VS _Autoload
Differencebetween $_Server['Request_Uri'] and $_Get['Q']
Store HTML Entities in Database? or Convert When Retrieved
How to Cause a Redirect to Occur Before PHP Script Finishes
Laravel Eloquent Compare Date from Datetime Field
How to Get User Image with Twitter API 1.1
Install Intl PHP Extension Osx High Sierra
Refresh a Part of Webpage in PHP
Zend_Form - Array Based Elements
What's the Best Way to Get the Fractional Part of a Float in PHP
Change the PHP Path to Mamps PHP
Cannot Start Session Without Errors in PHPmyadmin