php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #6117 next() fails when it reaches a "0" key
Submitted: 2000-08-12 02:20 UTC Modified: 2000-08-15 08:27 UTC
From: ronen at greyzone dot com Assigned:
Status: Closed Package: Documentation problem
PHP Version: 4.0.1pl2 OS: Redhat Linux 6.2
Private report: No CVE-ID: None
 [2000-08-12 02:20 UTC] ronen at greyzone dot com
When I use a for construct to step through an associative array, next() will stop when it reaches a key equivalent to "0".  "0" is treated like the end of the array, even if it is not.

SAMPLE CODE:
<?
$test[123]="one hundred twenty three";
$test[13]="thirteen";
$test[0]="zero";
$test[3]="three";
$test[11]="eleven";

// try the for construct:
for(reset($test);$key=key($test);next($test)) {
        echo "TEST[$key]=".$test[$key]."<br>";

}

echo "************************************<br>";

// try the foreach construct
foreach($test as $key => $value) {
        echo "TEST[$key]=$value<br>";
}

/***** THE OUTPUT IS:

TEST[123]=one hundred twenty three
TEST[13]=thirteen
************************************
TEST[123]=one hundred twenty three
TEST[13]=thirteen
TEST[0]=zero
TEST[3]=three
TEST[11]=eleven

****/

?>

Why does for not work, when foreach does?

Ronen.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2000-08-12 02:26 UTC] derick@php.net
It is not a bug, but a feature.

When $key=key($test) matches false ("0" is considered false), the loop ends. That's normal behaviour.
 [2000-08-12 10:34 UTC] waldschrott@php.net
I think it?s a docu bug, watch this from manual:

"If the array contains empty elements then this function
will return false for these elements as well. To properly
traverse an array which may contain empty elements see the
each() function."

Thus we should either treat this as a bug (backwards
incompatible!) or modify the docu

 [2000-08-15 08:27 UTC] jmoore@php.net
Updated Documentation, added a warning about 0 keys to the warning already given in the function.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Jul 27 00:01:30 2024 UTC