Re: [RFC] Add preserve_key_types to array_keys() to prevent unintended int conversion
| From: | Kamil Tekiela | Date: | Sat, 24 May 2025 15:55:31 +0000 |
| Subject: | Re: [RFC] Add preserve_key_types to array_keys() to prevent unintended int conversion | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-127443@lists.php.net to get a copy of this message | ||
As far as I know, this is how array keys are designed and changing
array_keys wouldn't solve the problem. The key is converted to the
appropriate type during creation. Array keys are defined as string|int
and expecting the values to be either string or int is a programming
error. Static analysis tools should catch that out.
If a developer remembers to use preserve_key_types then they would
also remember that the key can be string|int and would design the rest
of the code accordingly. So it seems to me like this solution is not
the right one.
I sympathise with the problem and I would prefer that the array keys
keep the type with which they were created. I have seen so many times
when a developer did something like this:
```
$arr = ['123' => 'foo'];
foreach ($arr as $key => $index) {
echo htmlentities($key);
}
```
Do I remember correctly that it was because of backwards compatibility
issues that this could not be changed?