note 127138 rejected from function.array-combine by cmb
| From: | cmb@php.net | Date: | Fri, 27 May 2022 11:21:19 +0000 |
| Subject: | note 127138 rejected from function.array-combine by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218535@lists.php.net to get a copy of this message | ||
Note Submitter: goran dot 100sic at gmail dot com
----
There is an inconsistent behavior in the function implementation that I'd like to warn about as
it may be very hard to debug on larger arrays, regarding members data type of the input array used
for keys. I have noticed this behavior in PHP version 5.5 and haven't tested it in any other
version.
Suppose the input array used for keys consists of members of string type, but some of those string
members by chance consist only of digit characters, so that they can be implicitly type-casted to a
valid integer. The implementation of array_combine() will do just that - in the resulting array the
string member from the keys array will be silently converted into integer type, turning that
resulting array member into regular indexed member instead of expected "key" =>
"value" pair.
Worse still, if the keys input array consists of mixed type members, containing both integer and
string type data, then there is a chance that inadvertently converted string member may duplicate
some other member being intentionally of integer type.
Here is my example on which I discovered this behavior.
The array used for keys is like this:
array (size=4)
0 => string '00000000' (length=8)
1 => string '22222222' (length=8)
2 => string 'AAAAAAAA' (length=8)
3 => string 'QQQQQQQQ' (length=8)
I needed to combine this array with an array of flags, like this:
array (size=4)
0 => string '0' (length=1)
1 => string '0' (length=1)
2 => string '1' (length=1)
3 => string '0' (length=1)
The result of array_combine($keys, $flags):
array (size=4)
'00000000' => string '0' (length=1)
22222222 => string '0' (length=1)
'AAAAAAAA' => string '1' (length=1)
'QQQQQQQQ' => string '0' (length=1)
Notice that a second member of a resulting array has lost the string data type and is converted into
integer type, making it an indexed member with an index 22222222 instead of intended
'22222222' => '0' pair.