xref: /PHP-7.0/tests/lang/foreachLoop.009.phpt (revision 97fe15db)
1--TEST--
2Foreach loop tests - foreach operates on the original array if the array is referenced outside the loop.
3--FILE--
4<?php
5// From php.net/foreach:
6// "Unless the array is referenced, foreach operates on a copy of the specified array."
7
8echo "\nRemove elements from a referenced array during loop\n";
9$refedArray=array("original.0", "original.1", "original.2");
10$ref=&$refedArray;
11foreach ($refedArray as $k=>$v1) {
12	array_pop($refedArray);
13	echo "key: $k; value: $v1\n";
14}
15
16echo "\nRemove elements from a referenced array during loop, using &\$value\n";
17$refedArray=array("original.0", "original.1", "original.2");
18$ref=&$refedArray;
19foreach ($refedArray as $k=>&$v2) {
20	array_pop($refedArray);
21	echo "key: $k; value: $v2\n";
22}
23
24echo "\nAdd elements to a referenced array during loop\n";
25$refedArray=array("original.0", "original.1", "original.2");
26$ref=&$refedArray;
27$count=0;
28foreach ($refedArray as $k=>$v3) {
29	array_push($refedArray, "new.$k");
30	echo "key: $k; value: $v3\n";
31
32	if ($count++>5) {
33		echo "Loop detected, as expected.\n";
34		break;
35	}
36}
37
38echo "\nAdd elements to a referenced array during loop, using &\$value\n";
39$refedArray=array("original.0", "original.1", "original.2");
40$ref=&$refedArray;
41$count=0;
42foreach ($refedArray as $k=>&$v4) {
43	array_push($refedArray, "new.$k");
44	echo "key: $k; value: $v4\n";
45
46	if ($count++>5) {
47		echo "Loop detected, as expected.\n";
48		break;
49	}
50}
51
52?>
53--EXPECT--
54
55Remove elements from a referenced array during loop
56key: 0; value: original.0
57key: 1; value: original.1
58key: 2; value: original.2
59
60Remove elements from a referenced array during loop, using &$value
61key: 0; value: original.0
62key: 1; value: original.1
63
64Add elements to a referenced array during loop
65key: 0; value: original.0
66key: 1; value: original.1
67key: 2; value: original.2
68
69Add elements to a referenced array during loop, using &$value
70key: 0; value: original.0
71key: 1; value: original.1
72key: 2; value: original.2
73key: 3; value: new.0
74key: 4; value: new.1
75key: 5; value: new.2
76key: 6; value: new.3
77Loop detected, as expected.
78
79