Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 215
cili Avatar asked Apr 29 '26 06:04

cili


1 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',).

like image 99
Peter Krauss Avatar answered Apr 30 '26 18:04

Peter Krauss