Aside from some trickery with objects that may or may not work, the only solution I can see is to make duck typing work for you instead of against you:
Prepend a space or 0 in front of the number. It will then be a string in the key " 25"
or "025"
, but will convert to an integer if you use it as a number or cast it as an integer elsewhere.
php > $arr = ['item_one', '025' => 'item_two'];
php > foreach($arr as $k => $v) {
php { if(is_int($k)) {
php { echo '['.$k.'] is not a custom key!';
php { }
php { }
[0] is not a custom key!
php >
Simply comparing the key to the position within the element is not reliable:
php > $arr = ['item_one','25'=>'item_two','2'=>'item_three'];
php > $i=0;
php > foreach($arr as $k=>$v) {
php { if($i != $k) {
php { echo '['.$k.'] is a custom key';
php { }
php { $i++;
php { }
[25] is a custom key
php >
(note: missed $arr['2'])
According to the manual:
The key can either be an integer or a string. The value can be of any type.
Additionally the following key casts will occur:
- Strings containing valid decimal integers, unless the number is preceded by a + sign, will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
- Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
- Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
Null will be cast to the empty string, i.e. the key null will actually be stored under "".
- Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.