xref: /PHP-5.4/tests/lang/foreachLoop.009.phpt (revision 176012df)
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
58
59Remove elements from a referenced array during loop, using &$value
60key: 0; value: original.0
61key: 1; value: original.1
62
63Add elements to a referenced array during loop
64key: 0; value: original.0
65key: 1; value: original.1
66key: 2; value: original.2
67key: 3; value: new.0
68key: 4; value: new.1
69key: 5; value: new.2
70key: 6; value: new.3
71Loop detected, as expected.
72
73Add elements to a referenced array during loop, using &$value
74key: 0; value: original.0
75key: 1; value: original.1
76key: 2; value: original.2
77key: 3; value: new.0
78key: 4; value: new.1
79key: 5; value: new.2
80key: 6; value: new.3
81Loop detected, as expected.
82
83