[prev in list] [next in list] [prev in thread] [next in thread]
List: php-doc-cvs
Subject: [DOC-CVS] =?utf-8?q?svn:_/phpdoc/en/trunk/language/control-structures/_foreach.xml?=
From: Christoph_Michael_Becker <cmb () php ! net>
Date: 2016-05-31 16:55:09
Message-ID: svn-cmb-1464713709-339246-1360844399 () svn ! php ! net
[Download RAW message or body]
cmb Tue, 31 May 2016 16:55:09 +0000
Revision: http://svn.php.net/viewvc?view=revision&revision=339246
Log:
fix #71458: foreach docs should expand upon the references warning
Bug: https://bugs.php.net/71458 (Open) foreach docs should expand upon the references warning
Changed paths:
U phpdoc/en/trunk/language/control-structures/foreach.xml
Modified: phpdoc/en/trunk/language/control-structures/foreach.xml
===================================================================
--- phpdoc/en/trunk/language/control-structures/foreach.xml 2016-05-30 17:51:21 UTC (rev 339245)
+++ phpdoc/en/trunk/language/control-structures/foreach.xml 2016-05-31 16:55:09 UTC (rev 339246)
@@ -73,6 +73,42 @@
</programlisting>
</informalexample>
</para>
+ <warning>
+ <para>
+ Reference of a <literal>$value</literal> and the last array element
+ remain even after the <literal>foreach</literal> loop. It is recommended
+ to destroy it by <function>unset</function>.
+ Otherwise you will experience the following behavior:
+ </para>
+ <informalexample>
+ <programlisting role="php">
+<![CDATA[
+<?php
+$arr = array(1, 2, 3, 4);
+foreach ($arr as &$value) {
+ $value = $value * 2;
+}
+// $arr is now array(2, 4, 6, 8)
+
+// without an unset($value), $value is still a reference to the last item: $arr[3]
+
+foreach ($arr as $key => $value) {
+ // $arr[3] will be updated with each value from $arr...
+ echo "{$key} => {$value} ";
+ print_r($arr);
+}
+// ...until ultimately the second-to-last value is copied onto the last value
+
+// output:
+// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
+// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
+// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
+// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
+?>
+]]>
+ </programlisting>
+ </informalexample>
+ </warning>
<para>
Referencing <literal>$value</literal> is only possible if the iterated array can be
referenced (i.e. if it is a variable). The following code won't work:
@@ -88,13 +124,6 @@
</programlisting>
</informalexample>
</para>
- <warning>
- <para>
- Reference of a <literal>$value</literal> and the last array element
- remain even after the <literal>foreach</literal> loop. It is recommended
- to destroy it by <function>unset</function>.
- </para>
- </warning>
<para>
<note>
<para>
--
PHP Documentation Commits Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic