svn: /phpdoc/en/trunk/language/control-structures/ foreach.xml

From: Date: Tue, 31 May 2016 16:55:09 +0000
Subject: svn: /phpdoc/en/trunk/language/control-structures/ foreach.xml
Groups: php.doc.cvs 
Request: Send a blank email to doc-cvs+get-14157@lists.php.net to get a copy of this message
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>

« previous php.doc.cvs (#14157) next »