php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #33368 String '0' not handled correctly in foreach
Submitted: 2005-06-16 20:35 UTC Modified: 2005-06-19 05:58 UTC
From: drphilosopher at yahoo dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.0.3 OS: Windows XP Service Patch 2
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: drphilosopher at yahoo dot com
New email:
PHP Version: OS:

 

 [2005-06-16 20:35 UTC] drphilosopher at yahoo dot com
Description:
------------
The string, '0', is not handled correctly 
in a foreach loop (and possibly elsewhere).

The first loop executes correctly.  The 
second and third loops perform incorrect
comparisons.  

In loops two and three, '0' == 'NOLIMIT'
evaluates to true when it should be false.


Reproduce code:
---------------
$arr = array('0' => '$0',
             '1000' => '$1,000', 
             '2000' => '$2,000', 
             '3000' => '$3,000', 
             'NOLIMIT' => 'NO LIMIT');
foreach ($arr as $key => $value)
{
    echo "$key : $value $hi\n";
}
echo "\n";
foreach ($arr as $key => $value)
{
    if ($key == 'NOLIMIT') { continue; }
    echo "$key : $value $hi\n";
}
echo "\n";
foreach ($arr as $key => $value)
{
    $hi = ($key == 'NOLIMIT' ? 'hi' : '');
    echo "$key : $value      $hi\n";
}

Expected result:
----------------
0 : $0 
1000 : $1,000 
2000 : $2,000 
3000 : $3,000 
NOLIMIT : NO LIMIT 

0 : $0 
1000 : $1,000 
2000 : $2,000 
3000 : $3,000 

0 : $0
1000 : $1,000      
2000 : $2,000      
3000 : $3,000      
NOLIMIT : NO LIMIT      hi

Actual result:
--------------
0 : $0 
1000 : $1,000 
2000 : $2,000 
3000 : $3,000 
NOLIMIT : NO LIMIT 

1000 : $1,000 
2000 : $2,000 
3000 : $3,000 

0 : $0      hi
1000 : $1,000      
2000 : $2,000      
3000 : $3,000      
NOLIMIT : NO LIMIT      hi

I am using PHP 5.03 and Apache 2.0.53 on Windows XP, service patch 2.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-06-16 21:12 UTC] tony2001@php.net
Please try using this CVS snapshot:

  http://snaps.php.net/php5-latest.tar.gz
 
For Windows:
 
  http://snaps.php.net/win32/php5-win32-latest.zip


 [2005-06-19 05:58 UTC] rasmus@php.net
No bug here, numeric strings in array indices have always been converted to integers.  So you are effectively doing 0=='NOLIMIT' and the integer representation of 'NOLIMIT' is 0.  You can use a === there to get what you want, or you can explicitly cast the $key to a string in the comparison.

  $hi = ((string)$key == 'NOLIMIT' ? 'hi' : '');

 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 03 10:01:33 2025 UTC