Due to serialization/deserialization of arrays I get incorrect data type of array keys in some cases.
$data = [
0 => 'item 1',
4 => 'item 2',
7 => 'item 3',
];
$storage->set( 'demo', $data );
// ...and get it back later
$data = storage->get( 'demo' );
var_dump( $data );
/*
Result:
array (size=3)
"0" => string "item 1"
"4" => string "item 2"
"7" => string "item 3"
But I need (keys must be int):
array (size=3)
0 => string "item 1"
4 => string "item 2"
7 => string "item 3"
*/
Question: Is there an easy way to convert the keys back to integer?
I tried array_reverse( array_map( 'intval', array_reverse( $data ) ) ) but this loses items with different keys but identical values and most importantly it has problems with non-numeric keys.
Also array_values( $data ) did not solve the problem due to similar problems: It loses non-numeric keys and also keys are not sequential (it can be 0, 4, 7, but array_values() will assign keys 0, 1, 2)
Update - why this is important for my
We had problems with some website configuration because of this:
$data['0']returns'item1'but$data[0]returnsnull
foreach. Though I can't imagine situation why you need this.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.