Bug #79525 [Com]: Foreach converting/casting array keys to int
| From: | data dot protection dot gdpr at gmail dot com | Date: | Sun, 26 Apr 2020 21:51:30 +0000 |
| Subject: | Bug #79525 [Com]: Foreach converting/casting array keys to int | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-226784@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=79525&edit=1
ID: 79525
Comment by: data dot protection dot gdpr at gmail dot com
Reported by: data dot protection dot gdpr at gmail dot com
Summary: Foreach converting/casting array keys to int
Status: Not a bug
Type: Bug
Package: Arrays related
Operating System: CentOS 6
PHP Version: 7.3.17
Assigned To: cmb
Block user comment: N
Private report: N
New Comment:
That really doesn't seem like a good behavior, and this can definitely lead to unexpected
behavior.
In PHP, we have ways to do strict comparisons (in_array(.., .., true), ===),
and honestly, this key conversion kind of defeats the purpose.
I hope that a change to this will be considered in the future.
If I'm using quotes, I want a string, not an int... I thought this was common sense.
Previous Comments:
------------------------------------------------------------------------
[2020-04-26 21:45:16] cmb@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
Like bugreports@ said above.
------------------------------------------------------------------------
[2020-04-26 21:43:24] bugreports at gmail dot com
> I have an array with "numeric" key as string (e.g. '1')
you don't, you just think you do
php > var_dump([1=>'a', 2=>'b']);
array(2) {
[1]=>
string(1) "a"
[2]=>
string(1) "b"
}
php > var_dump(['1'=>'a', '2'=>'b']);
array(2) {
[1]=>
string(1) "a"
[2]=>
string(1) "b"
}
------------------------------------------------------------------------
[2020-04-26 21:31:59] data dot protection dot gdpr at gmail dot com
Description:
------------
I have an array with "numeric" key as string (e.g. '1'), intentionally, as
semantically it makes sense for the context.
However, I noticed that using a foreach will convert the numeric string keys to "int",
which then causes problems with strict comparisons, for example.
This does not seem like a good behavior, and I wonder if this should change.
Test script:
---------------
<?php
$array = array(
'' => 'test',
'1' => 'test1',
'5' => 'test5',
'2' => 'test2',
'10' => 'test10'
);
foreach ($array as $key => $val) {
var_dump($key);
}
Expected result:
----------------
string(0) ""
string(1) "1"
string(1) "5"
string(1) "2"
string(2) "10"
Actual result:
--------------
string(0) ""
int(1)
int(5)
int(2)
int(10)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=79525&edit=1