I've carefully read the discussion at [https://externals.io/message/116735].
While I understand the historical reasons make it difficult to directly
change array behavior, this automatic conversion issue does confuse many
PHP developers and needs to be addressed. I'd like to propose two solutions:

   1.

   First, we could add a parameter like preserve_key_types to array
   functions such as array_keys()/array_search() to temporarily handle the
   implicit conversion issue.
   2.

   Alternatively, we could introduce a new data type "Map" (inspired by
   Java and other languages) to completely solve this conversion problem:

php
复制

// Declaration (preserves original key types)$map = new Map(['01' =>
'a', '10' => 'b']); // Explicit declaration, keys "01" and "10" won't
convert to int$map = {"01"=>111, "02"=>222}; // Syntactic sugar for
the above line, similar to array's [] syntax

This Map type would support conversion to/from traditional arrays:

php
复制

$array = [1, 2, 3];$map = Map::fromArray($array); // Explicit conversion
$newArray = $map->toArray(); // Convert back to traditional array

During iteration, keys would maintain their original types:

php
复制

foreach ($map as $key => $value) {
    // $key preserves its original type (string/int)
}

Existing functions like array_keys()/array_search() could accept Map
parameters while maintaining all other logic identical to traditional
arrays, except keys wouldn't be implicitly converted.



[xiaoma]

Daikaras <webmas...@daikaras.lt> 于2025年5月27日周二 15:42写道:

> As Kamil mentioned, this is not limited to a single function but to array
> type as a whole. See previous discussion
> https://externals.io/message/116735.
>
> On 5/24/2025 6:43 PM, 马正强 wrote:
>
> I propose adding a preserve_key_types parameter to array_keys() to
> address issues caused by automatic conversion of string-numeric keys to
> integers.
>
>
>

Reply via email to