2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-05-11 12:02:15 +02:00
In PHP, references provide a way to access the same variable content using different names.
2021-04-28 16:49:39 +02:00
2023-05-11 12:02:15 +02:00
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.
2021-04-28 18:08:03 +02:00
2023-05-11 12:02:15 +02:00
=== What is the potential impact?
2021-04-28 16:49:39 +02:00
2023-05-11 12:02:15 +02:00
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]
2021-04-28 16:49:39 +02:00
----
$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';
----
2023-05-11 12:02:15 +02:00
==== Compliant solution
2021-04-28 18:08:03 +02:00
2023-05-11 12:02:15 +02:00
[source,php,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
$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;
}
2023-05-11 12:02:15 +02:00
unset($value);
2021-04-28 16:49:39 +02:00
$value = 'x';
----
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
2023-05-11 12:02:15 +02:00
=== 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
2021-11-05 16:23:43 +01:00
* https://schlueters.de/blog/archives/141-References-and-foreach.html[References and Foreach]
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
2023-05-11 12:02:15 +02:00
2021-09-20 15:38:42 +02:00
== Implementation Specification
2023-05-11 12:02:15 +02:00
2021-09-20 15:38:42 +02:00
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]