Bug #71454 [Opn->Nab]: foreach last element is copy of penultimate, with array of DateIntervals

From: Date: Tue, 26 Jan 2016 13:59:11 +0000
Subject: Bug #71454 [Opn->Nab]: foreach last element is copy of penultimate, with array of DateIntervals
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-198903@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=71454&edit=1 ID: 71454 Updated by: rasmus@php.net Reported by: qdinar at gmail dot com Summary: foreach last element is copy of penultimate, with array of DateIntervals -Status: Open +Status: Not a bug Type: Bug Package: Date/time related Operating System: windows 10 PHP Version: Irrelevant Block user comment: N Private report: N New Comment: This is completely expected. If you unroll your loops you can see why. eg. $interv = & $intervals[0]; $interv = & $intervals[1]; ... $interv = & $intervals[6]; Now you are at the end of your first loop and as you can see $interv is a reference to $intervals[6]; So at this point if you were to do: $interv = 123; it would be equivalent to doing: $intervals[6] = 123; So now when we unroll your 2nd loop you are doing: $interv = $intervals[0]; $interv = $intervals[1]; ... $interv = $intervals[6]; which since $interv is a reference to $intervals[6] is actually doing: $intervals[6] = $intervals[0]; $intervals[6] = $intervals[1]; ... $intervals[6] = $intervals[5]; // which is 5, of course $intervals[6] = $intervals[6]; // still 5 It has to work this way because a loop has to be equivalent to its unrolled version. If you want to avoid side-effects like that, unset($interv) before the second loop. This is documented on http://php.net/foreach Previous Comments: ------------------------------------------------------------------------ [2016-01-26 11:54:49] qdinar at gmail dot com i have found a quick fix / workaround for this bug: use foreach($intervals as &$interv) (ie &$interv also in second foreach). ------------------------------------------------------------------------ [2016-01-26 11:51:34] qdinar at gmail dot com Description: ------------ foreach through array of DateIntervals gives penultimate element instead of last element Test script: --------------- $intervals=array(1,2,3,4,5,6); foreach($intervals as &$interv){ $interv = new DateInterval('PT'.$interv.'M'); } $time = new DateTime('6:20'); foreach($intervals as $interv){ echo ','.$interv->format('%i'); } Expected result: ---------------- ,1,2,3,4,5,6 Actual result: -------------- ,1,2,3,4,5,5 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=71454&edit=1

« previous php.bugs (#198903) next »