== Why is this an issue?

In PHP, references allow you to create multiple names for the same variable, enabling you to access and manipulate its value through different identifiers.
They are denoted by the ampersand symbol & placed before the variable name during declaration or assignment.

When a reference is used in a ``++foreach++`` loop instead of using a simple variable, the reference remains assigned and keeps its "value" which is a reference, even after the ``++foreach++`` execution.

=== What is the potential impact?

Not unsetting the reference can lead to bugs later in the code, as most of the time, this behavior is different from what the developer is expecting.
For example, the reference may be used incorrectly with the previous value.

To avoid unexpected side effects, it is recommended to always ``++unset++`` a reference that is used in a ``++foreach++`` loop.

== How to fix it in Core PHP

Unset the reference that is used in the ``++foreach++`` loop.

=== Code examples

==== Noncompliant code example

[source,php,diff-id=1,diff-type=noncompliant]
----
$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Noncompliant; $value is still alive after the loop and references the last item of the array: $arr[2]
    $value = $value * 2;
}
$value = 'x';
----

==== Compliant solution

[source,php,diff-id=1,diff-type=compliant]
----
$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Compliant; there is no risk to use by mistake the content of $value pointing to $arr[2]
    $value = $value * 2;
}
unset($value);
$value = 'x';
----

== Resources

=== Documentation

PHP Documentation:

* https://www.php.net/manual/en/language.references.php[References]
* https://php.net/manual/en/control-structures.foreach.php[Foreach]

=== Articles & blog posts

* https://schlueters.de/blog/archives/141-References-and-foreach.html[References and Foreach]

ifdef::env-github,rspecator-view[]

'''

== Implementation Specification

(visible only on this page)

=== Message

Unset XXX just after the end of the foreach loop to avoid side effects.


=== Highlighting

The reference declaration in the foreach.


endif::env-github,rspecator-view[]
