|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2020-11-02 22:49 UTC] shop1 at mokraemer dot de
Description:
------------
numerical array keys are converted to integers.
In strict mode (typed properties, typed function parameters), this is not desireable.
Test script:
---------------
declare(strict_types=1);
function f(string $s):string{
return $s;
}
$array=[
'x'=>5,
'1'=>6
];
foreach($array as $k => $v){
echo f($k);
}
Expected result:
----------------
x1
Actual result:
--------------
xPHP Fatal error: Uncaught TypeError: Argument 1 passed to f() must be of the type string, int given, called in /tmp/test.php on line 13 and defined in /tmp/test.php:3
Stack trace:
#0 /tmp/test.php(13): f()
#1 {main}
thrown in /tmp/test.php on line 3
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 21:00:01 2025 UTC |
it is true, this is documented behaviour, but with strict types this becomes a problem. Since array keys do not keep the original type. If this is kept, it means every array key must be explicitly converted back to string. Using e.g. array_keys($array) to pass an array of strings does not work, you always have to reaply array_map('strval',array_keys($array)) This makes everything errorprone, it is hard to detect those errors, as users/databases,... may be the source of those values.