Q:

forEach

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
2
foreach (array as $value){ 
  //code to be executed; 
  print("value : $value");
} 

foreach (array as  $key => $value){ 
  //code to be executed; 
  print("key[$key] => $value");
} 
8
var colors = ['red', 'blue', 'green'];

colors.forEach(function(color) {
  console.log(color);
});
44
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})
28
let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
});
// one
// two
// three
// four
21
var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
    console.log(color);
});
13
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));
20
var items = ["item1", "item2", "item3"]
var copie = [];

items.forEach(function(item){
  copie.push(item);
});
11
let array = ['Item 1', 'Item 2', 'Item 3'];

array.forEach(item => {
	console.log(item); // Logs each 'Item #'
});
6
users.forEach((user, index)=>{
	console.log(index); // Prints the index at which the loop is currently at
});
5
const arraySparse = [1,3,,7]
let numCallbackRuns = 0

arraySparse.forEach((element) => {
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.
5

New to Communities?

Join the community