alex alex - 7 months ago 23
PHP Question

How can I force PHP to use strings for array keys?

I've come across an old app that uses an id to name type array, for example...

array(1) {
[280]=>
string(3) "abc"
}


Now I need to reorder these, and a
var_dump()
would make it appear that that isn't going to happen while the keys are integers.

If I add an
a
to every index,
var_dump()
will show double quotes around the key, my guess to show it is now a string...

array(1) {
["280a"]=>
string(3) "abc"
}


This would let me easily reorder them, without having to touch more code.

This does not work.

$newArray = array();
foreach($array as $key => $value) {
$newArray[(string) $key] = $value;
}


A
var_dump()
still shows them as integer array indexes.

Is there a way to force the keys to be strings, so I can reorder them without ruining the array?

Answer

EDIT:

I assumed that if they are integers, I can't reorder them without changing the key (which is significant in this example). However, if they were strings, I can reorder them how they like as the index shouldn't be interpreted to have any special meaning. Anyway, see my question update for how I did it (I went down a different route).

Actually they dont have to be in numeric order...

array(208=>'a', 0=> 'b', 99=>'c');

Is perfectly valid if youre assigning them manually. Though i agree the integer keys might be misinterpreted as having a sequential meaning by someone although you would think if they were in a non-numeric order it would be evident they werent. That said i think since you had the leeway to change the code as you updated that is the better approach.


Probably not the most efficient way but easy as pie:

$keys = array_keys($data);

$values = array_values($data);
$stringKeys = array_map($keys, 'strval');

$data = array_combine($stringKeys, $values);

//sort your data