3

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!

Community
  • 1
  • 1
cili
  • 1,037
  • 2
  • 19
  • 34
  • 4
    I'm not sure I understand. `array(5 => 'foo')` creates an array with an integer key 5 and value foo. It doesn't *force* it to start at 0. Are you doing any kind of sorting? That could cause PHP to re-index the keys. Seeing code would help. – Mike B Sep 27 '11 at 12:40

2 Answers2

3

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

Peter Krauss
  • 13,174
  • 24
  • 167
  • 304
0

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.

Kenny
  • 5,350
  • 7
  • 29
  • 43
  • 4
    His KEYS are int/string, not the value. And by the time he has his final array it's already fubared. I don't see how this could help. – Mike B Sep 27 '11 at 12:49
  • Added a solution for that too right after the Edit:. Best is to always make sure the data is set correctly in the array on the initial filling ofcourse. – Kenny Sep 27 '11 at 13:13