Doc #80296 [Opn->Ver]: Migration docs regarding foreach needs examples and clarification
Edit report at https://bugs.php.net/bug.php?id=80296&edit=1
ID: 80296
Updated by: cmb@php.net
Reported by: php4fan at gmail dot com
Summary: Migration docs regarding foreach needs examples and
clarification
-Status: Open
+Status: Verified
Type: Documentation Problem
Package: Documentation problem
Operating System: all
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
UPGRADING has a nice example[1], but that is neither in the
migration guide nor in the manual proper.
[1] <https://3v4l.org/DIEqs>
Previous Comments:
------------------------------------------------------------------------
[2020-10-29 17:42:46] php4fan at gmail dot com
Description:
------------
---
From manual page: https://www.php.net/manual/en/migration70.incompatible.php#migration70.incompatible.foreach.by-value
---
It says:
"""
foreach by-value operates on a copy of the array ¶
When used in the default by-value mode, foreach will now operate on a copy of the array being
iterated rather than the array itself. This means that changes to the array made during iteration
will not affect the values that are iterated.
"""
It is unclear what this means, because what I understand from it is not true.
Also, an example should be given, with different output for 5.x vs 7.x.
Even if the explanation wasn't ambiguous as it is, an example should ALWAYS be given for all
documented changes.
Test script:
---------------
Consider these scripts:
<?php // EXAMPLE 1
$a = ['x', 'y', 'z'];
foreach ($a as $i => $v) {
$a[$i] = '!!!';
}
print_r($a);
?>
<?php // EXAMPLE 2
$a = ['x', 'y', 'z'];
foreach ($a as $v) {
$a[1] = '!!!';
}
print_r($a);
?>
Expected result:
----------------
In PHP 5, the first example outputs:
Array
(
[0] => !!!
[1] => !!!
[2] => !!!
)
and example 2 outputs:
Array
(
[0] => x
[1] => !!!
[2] => z
)
as expected.
From the confusing statement cited above, I would seem to understand (and that would surprise me)
that the first example in PHP 7 would output:
Array
(
[0] => x
[1] => y
[2] => z
)
or perhaps, that example 1 would work as in PHP 5, but that example 2 would output
Array
(
[0] => x
[1] => y
[2] => z
)
Actual result:
--------------
Fortunately, that is not the case. But then, I'm completely lost as to what the sentence means.
I can't figure out an example where the behavior in PHP 5 and 7 would differ.
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=80296&edit=1
Thread (6 messages)