PHP - Cast int key to string? [duplicate]
I have a few large PHP functions written some time ago. They contain some associative arrays. Until now, I had no problem with these arrays because they contained keys of type string and int (like "brown" and 118). The problem is, when the keys are all int, they are not kept, instead the are converted to 0, 1 etc.
Is there any way to force an array to keep the keys I give to it, even if they are all int? The functions are pretty large and it would take too long to change them.
EDIT
As Mike B intuited, I use a sorting function which seems to reindex the arrays. I was using a function I found here: Sort an Array by keys based开发者_JAVA百科 on another Array?
It was the first one, the one of Erin, but it didn't keep the correct indexes. I tried the version edited by Boombastic and it works well.
Thanks for all your answers!
I have similar problem with $array = ['00'=>'x','11'=>'y']
that was converted to integer keys, losting a '0' digit.
Writing only to offer an answer 5 years after...
The KennyDs answer can be simplified by,
$array = array_map('strval',$array);
... but, as MikeB commented, KennyDs answer is wrong, the correct is:
foreach($array as $key => $val)
$array[(string) $key] = $val;
or in a (ugly) functional style,
$array = array_flip( array_map('strval', array_flip($array)) );
(no direct way as I checked).
About check by var_dump()
or var_export()
: show string as number when parse as number (eg. '123'
as 123
), but, it not lost string (!), the example array ( '00' => 'x', 11 => 'y',)
.
You could also just go over the array and cast all the int's to a string?
foreach($array as $key => $val){
$array[$key] = (string)$val;
}
Edit: if you need your keys to be int then just make sure when you are filling the array you add an (int) cast before the $key.
精彩评论