Using next() inside a foreach

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello,

I'm hesitant to report this issue as a bug, since I see other bugs
(43890 and 43220) already opened describing similar, but not identical,
issues.  The latter bug is described as a documentation issue...

In my tests all versions of php prior to 5.2.4, foreach does NOT
increment the array pointer for each iteration, at least not at the top
of the loop.  This new behavior in 5.2.4 breaks array look-ahead logic,
when using next() -- since you end up looking TWO places ahead instead
of one.

This produces the effect that in the body of the loop, current()
actually returns the "next" value in the array -- which is the
workaround I've implemented in my code for doing a look-ahead -- though
it seems non-intuitive to have current() return the next value.

Perhaps the previous behavior was to increment the array pointer at the
END of the foreach block, and now for some reason it's incrementing it
at the BEGINNING?  That would explain it I guess...

Perhaps there's a better way to do look-ahead, but for a behavior change
like this, if it's intentional, shouldn't it at least be in the
"Backward Compatibility" section of the migration docs?

Example Code:

$test_arr = array('zero', 'one','two','three','four');

foreach ($test_arr as $idx => $val) {

	$next_val = next($test_arr);

	print "This: " . $idx . " -> " . $val . "\n";
	print "Next: " . $next_val . "\n";

}

---------------------------------------------
output under v5.2.3 (and 4.4.8):
---------------------------------------------

This: 0 -> zero
Next: one
This: 1 -> one
Next: two
This: 2 -> two
Next: three
This: 3 -> three
Next: four
This: 4 -> four
Next:

-------------------------------
output under v5.2.4 and v5.2.5:
-------------------------------

This: 0 -> zero
Next: two
This: 1 -> one
Next: three
This: 2 -> two
Next: four
This: 3 -> three
Next:
This: 4 -> four
Next:

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

Regards to All,

-Erik

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux