[prev in list] [next in list] [prev in thread] [next in thread] 

List:       php-doc-bugs
Subject:    [DOC-BUGS] Doc #71458 [Opn]: foreach docs should expand upon the references warning
From:       bwoebi () php ! net
Date:       2016-01-28 12:43:12
Message-ID: 201601281243.u0SChCIQ015098 () sgrv20 ! php ! net
[Download RAW message or body]

Edit report at https://bugs.php.net/bug.php?id=71458&edit=1

 ID:                 71458
 Updated by:         bwoebi@php.net
 Reported by:        requinix@php.net
 Summary:            foreach docs should expand upon the references
                     warning
 Status:             Open
 Type:               Documentation Problem
 Package:            Scripting Engine problem
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

Another option though would be to change behavior (in next major) and deref foreach \
() references at the end of the loop...


Previous Comments:
------------------------------------------------------------------------
[2016-01-26 19:51:38] requinix@php.net

Description:
------------
Every other month there's a bug report about how having two foreach loops, the first \
with a reference and the second without, results in unexpected behavior. (The bug \
system suggested four of them to me now as possible duplicates of this.)

While there is a warning in the documentation,

"Warning
Reference of a $value and the last array element remain even after the foreach loop. \
It is recommended to destroy it by unset()."

an example would be helpful to illustrate what the effects of that can look like to a \
developer. Plus it would make the warning box larger and more visible.

An example such as:



Test script:
---------------
<?php

$array = [1, 2, 3, 4, 5];

foreach ($array as &$n) {
	// $n is a reference to an item in $array
	$n = $n * 2;
}
// $array == [2, 4, 6, 8, 10]

// without an unset($n), $n is still a reference to the last item: $array[4]

foreach ($array as $k => $n) {
	// $array[4] will be updated with each value from $array...
	echo "{$k} => {$n} ";
	print_r($array);
}
// ...until ultimately the second-to-last value is copied onto the last value

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 6 )
// 3 => 8 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 8 )
// 4 => 8 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 8 )

?>



------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=71458&edit=1

-- 
PHP Documentation Bugs 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