|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2003-05-14 03:50 UTC] nicolas at van-lancker dot be
According to the documentation :
Also note that foreach operates on a copy of the specified array, not the array itself, therefore the array pointer is not modified as with the each() construct and changes to the array element returned are not reflected in the original array. However, the internal pointer of the original array is advanced with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array.
Given the code :
<?php
$arr = array("one", "two", "three");
echo "current : " . current($arr) . "<br>";
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br>";
}
echo "after for each : " . current($arr) . "<br>";
?>
Code result :
current : one
Key: 0; Value: one
Key: 1; Value: two
Key: 2; Value: three
after for each :
It seems that the internal array pointer indeed has been moved while iterating. But I would expect that it should be a the end of the original array, returning me a value "three" instead of nothing. When calling prev($arr); it still doesn't return anything. Maybe the interal array pointer has gone beserk?
This might be a wrong reflexion by me and not be a bug. But it find it a bit confusing...
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Mar 04 14:00:01 2026 UTC |
This is more common problem: <?php $arr = array("one", "two", "three"); var_dump(current($arr)); foreach ($arr as $v); var_dump(current($arr)); reset($arr); var_dump(current($arr)); while(each($arr)); var_dump(current($arr)); ?> And output is: string(3) "one" bool(false) string(3) "one" bool(false) So, as you can see, it's not just foreach(), each() also does the same, ie. sets current key to null. IMO, current documentation is correct about it. (the key should be set to the last key) The question is if it should be fixed, as it's propably been around there since the beginning..but I leave that decision to Zeev / Andi. For the moment, leave this as 'Verified'.