php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #77614 Array: mixed keys problem in foreach loop
Submitted: 2019-02-13 18:04 UTC Modified: 2019-02-14 04:45 UTC
From: shorvat at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: Irrelevant OS: Win 10 & Ubuntu server
Private report: No CVE-ID: None
 [2019-02-13 18:04 UTC] shorvat at gmail dot com
Description:
------------
PHP 7.0.10 & 5.6.25

Key comparation in foreach loop not working as expected when keys are of mixed types (strings and ints)

If I use triple-equals operator (===) it works just fine, but it seems it should work with double-equals operator (==) as well.

Test script:
---------------
$array = array();

$array['word'] = "test 1";
$array['0'] = "test 2";
$array['1'] = "test 3";

foreach($array as $k=>$v) {
    var_dump($k);
    if($k == "word") {
        continue;
    }

    print_r($v);
}

Expected result:
----------------
C:\wamp64\www\tst\array_bug.php:10:string 'word' (length=4)
C:\wamp64\www\tst\array_bug.php:10:int 0
test 2
C:\wamp64\www\tst\array_bug.php:10:int 1
test 3

Actual result:
--------------
C:\wamp64\www\tst\array_bug.php:10:string 'word' (length=4)
C:\wamp64\www\tst\array_bug.php:10:int 0
C:\wamp64\www\tst\array_bug.php:10:int 1
test 3

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-02-13 18:08 UTC] rtheunissen@php.net
This is because `"word" == 0` is true.

See https://3v4l.org/A66OG
 [2019-02-13 18:14 UTC] shorvat at gmail dot com
That's right. But 'word' == '0' is false
 [2019-02-13 19:28 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2019-02-13 19:28 UTC] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

http://php.net/manual/en/language.types.array.php
> Additionally the following key casts will occur:
>
> * Strings containing valid decimal integers, unless the number is preceded by a
> + sign, will be cast to the integer type. E.g. the key "8" will actually be
> stored under 8. On the other hand "08" will not be cast, as it isn't a valid
> decimal integer.

As the var_dump shows, $k === 0.
 [2019-02-13 20:55 UTC] spam2 at rhsoft dot net
> That's right. But 'word' == '0' is false

no it is not

$array['0'] becomes implicit $array[0]

php > echo (int)"word";
0

http://php.net/manual/en/language.types.type-juggling.php
http://php.net/manual/en/types.comparisons.php
 [2019-02-14 04:45 UTC] shorvat at gmail dot com
I did not read documentation well enough apparently. Sorry.

At a time, when I reported this "bug", I thought that $array['0'] is not the same as $array[0].
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 20:01:45 2024 UTC