1$arr = ['Item 1', 'Item 2', 'Item 3'];
2
3foreach ($arr as $item) {
4 var_dump($item);
5}
1foreach (array as $value){
2 //code to be executed;
3 print("value : $value");
4}
5
6foreach (array as $key => $value){
7 //code to be executed;
8 print("key[$key] => $value");
9}
1
2<?php
3$arr = array(1, 2, 3, 4);
4foreach ($arr as &$value) {
5 $value = $value * 2;
6}
7// $arr is now array(2, 4, 6, 8)
8
9// without an unset($value), $value is still a reference to the last item: $arr[3]
10
11foreach ($arr as $key => $value) {
12 // $arr[3] will be updated with each value from $arr...
13 echo "{$key} => {$value} ";
14 print_r($arr);
15}
16// ...until ultimately the second-to-last value is copied onto the last value
17
18// output:
19// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
20// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
21// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
22// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
23?>
24
25
1
2<?php
3$arr = array(1, 2, 3, 4);
4foreach ($arr as &$value) {
5 $value = $value * 2;
6}
7// $arr is now array(2, 4, 6, 8)
8unset($value); // break the reference with the last element
9?>
10
11
1
2<?php
3foreach (array(1, 2, 3, 4) as &$value) {
4 $value = $value * 2;
5}
6?>
7
8
1
2<?php
3$array = [
4 [1, 2],
5 [3, 4],
6];
7
8foreach ($array as list($a, $b)) {
9 // $a contains the first element of the nested array,
10 // and $b contains the second element.
11 echo "A: $a; B: $b\n";
12}
13?>
14
15