xref: /PHP-7.4/tests/lang/foreachLoop.009.phpt (revision d679f022)
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--
54Remove elements from a referenced array during loop
55key: 0; value: original.0
56key: 1; value: original.1
57key: 2; value: original.2
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
67
68Add elements to a referenced array during loop, using &$value
69key: 0; value: original.0
70key: 1; value: original.1
71key: 2; value: original.2
72key: 3; value: new.0
73key: 4; value: new.1
74key: 5; value: new.2
75key: 6; value: new.3
76Loop detected, as expected.
77