Change value of a variable inside foreach loop? Make it available outside the loop
This is because you are re-declaring the variable with var
in the loop instead of just updating/setting it. Re-declaring it wipes out the earlier variable of the same name from the previous loop iteration and hides the one from the function in the higher scope. It establishes a new one instead of just updating the value in the existing one.
var arr = ["one"];var str = 0;arr.forEach(function(part){ if(part == 'one') { str = 1; console.log('str changed to: ' + str); }})
console.log('str is now: ' + str);
PHP foreach update the variable outside of foreach and use it inside again
In a comment, @NanThiyagan wrote:
"your question was not clear.but your code works fine refer
eval.in/1050113"
Check out the output. It says 5.0000001. This might give you a hint that php automatically does something to round up your value.
Read this: http://php.net/manual/en/language.types.float.php
And pay attention to the part:
"So never trust floating number results to the last digit, and do not
compare floating point numbers directly for equality."
In this article they approach the problem with an implicit precision: https://www.leaseweb.com/labs/2013/06/the-php-floating-point-precision-is-wrong-by-default/
Like this:
ini_set('precision', 17);
echo "0.1 + 0.2 = ". ( 0.1 + 0.2 ) ."\n";
$true = 0.1 + 0.2 == 0.3 ? "Equal" : "Not equal";
echo "0.1 + 0.2 = 0.3 => $true\n";
Changing a value of a variable inside foreach loop PHP
try this instead :
$returnValue = "";
foreach($vinArray as $k=>$vinValue){
$sql_vin_check = "SELECT count(*) c FROM users WHERE vin LIKE '%:vin%'";
$stmtvincheck = $pdo->prepare($sql_vin_check);
$stmtvincheck->bindParam(':vin', $vinValue);
$stmtvincheck->execute();
$vinCheck = $stmtvincheck->fetch();
$stmtvincheck->closeCursor();
if($vinCheck['c'] > 0){
$returnValue = $vinValue;
break;
}
}
return $returnValue;
i'd also suggest you replace the returnvalue/break with a direct return from there if nothing else is expected (this suggestion have nothing to do with your problem)
change value of variable in forEach loop java 8
Considering lambdas are essentially syntactic sugar for an anonymous inner class, a variable used in a lambda expression must be effectively final. Check out this post for more details.
How to make variable global outside foreach loop in php?
You need to define the variable outside loop if you want to access it outside as well.
$folder = $obj->get_all_folders();
$existing_directory = null;
foreach ($folder as $folder_data)
{
$existing_directory = $folder_data['root_dir'];
}
as per your code you will get last record from array
so you can try below code as well
$folder = $obj->get_all_folders();
$last_record = end($folder);
$existing_directory = $last_record['root_dir'];
Can't acess variable outside forEach loop JavaScript
Async functions don't do what you think they do in forEach
. Foreach will wait for every loop, but since it won't return a Promise
, you can't actually wait for all loops (the forEach
) to be done - the method will just return the current null immediately. Then you log that once. You might notice that your last log is logged first, and your others later, indicating that forEach
was completed, but the loops completed later, and your array only filled up after your first log.
Personally, I would suggest using a for
loop itself instead, which does not actually take you out of the async flow:
const allItems = [];
for( const element of orderPads ){
for( const elem of element.orders_fk ){
const itemsArray = await OrderedItem.find({ order_fk: elem });
for( const e of itemsArray ){
const temp = e.toObject();
const mesa = await Table.findById(element.mesa);
temp.mesa = mesa.name;
allItems.push(temp)
console.log(allItems)
}
}}
console.log(allItems)
Variable outside foreach loop
$date_array = array();
if( !empty($row_edit) ){
$stageDates = explode(', ',$row_edit['placement_stage_date']);
foreach( $stageDates as $stageDate ){
//echo $stageDate.'<br/>';
$date_array[] = $stageDate;
}
}
// print $stageDate value outside of loop, something like this
<input type="text" name="placement_stage_date[]" value="<?php echo $date_array[0]; ?>" />
<input type="text" name="placement_stage_date[]" value="<?php echo $date_array[1]; ?>" />
<input type="text" name="placement_stage_date[]" value="<?php echo $date_array[2]; ?>" />
declare variable outside of the foreach loop
Well, you can do:
string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
name = loopName;
// other stuff
}
Or more likely:
string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
if (someCondition.IsTrueFor(loopName)
{
name = loopName;
break;
}
}
If the contents of the foreach loop is just to find a matching element - which at least sounds likely - then you should consider whether LINQ would be a better match:
string name = names.Where(x => x.StartsWith("Fred"))
.FirstOrDefault();
Using LINQ can often make code which is basically trying to find something a lot simpler to read.
Related Topics
Check If a String Is HTML or Not
Get Docx File Contents Using Javascript/Jquery
Button Enabled and Disabled Based on Checkbox Is Checked or Not
Javascript Generate Random Numbers Without Repeating
Keep Order of Objects Inside a Json String After They Are Parsed
Use Localstorage Across Subdomains
How to Redirect Url After Login Successful Via Ajax Call in PHP
How to Show a Confirm Message Before Delete
React Router Dom Returns a Blank Page When Going to a Particular Route
Blob Download Is Not Working in Ie
How to Combine First Name and Last Name in JavaScript
Vuejs Error, Invalid Prop: Type Check Failed for Prop. Expected Date, Got Number With Value
Change Specific Button Text on Click Inside Ngfor
How to Tell Chrome Web Debugger to Show the Current Mouse Position in Page Coordinates
Use Lodash to Find Objects in an Array Matches an Id (Complex, Drilldown)
How to Import Modules from All Files in a Directory, Using a Wildcard
Angularjs Directive Does Not Update on Scope Variable Changes