AFAIK, there are no core PHP methods which allow you to re-key an array.
Okay, that's not entirely true - there is array_change_key_case()
, but whenever I need to change an array's keys it's never been this use case.
You could do it with a foreach
loop:
$newArray = [];
foreach ($oldArray as $key => $value) {
// TODO: $newKey = ...;
$newArray[$newKey] = $value;
}
But that's not very clean (nor functional). Alternatively, you could do this:
$newArray = array_combine(
array_map(function ($value) {
// TODO: return new key here
}, array_values($oldArray)),
array_values($oldArray)
);
But that's way too much code for such a simple action. And it's not immediately clear what you're trying to do.
I propose implementing a new function which behaves exactly like that long array_combine
example above. Perhaps this new function might be called array_change_keys()
. This would take two parameters:
- An
array
you want to re-key - A
callable
which is executed for each element of the array
That callable
would take one or two parameters:
- The value of the current item
- The old key of that item (not sure if this is really needed)
Whatever the callable
return becomes the new key for that item. If that new key is not an int
, PHP will try to cast to a string
.
So it's sort of like array_map
or array_walk
, but it modifies the keys instead (and keeps the values the same).
Let's say we want to take an array of some entities and re-key them by id:
array_change_keys($entities, function($value) { return $value->getId(); });
Or if we wanted to re-key an array of strings by their MD5 hash:
array_change_keys($strings, 'md5');
- Should this create a new array (like
array_map
) or modify the current one (likesort
)?- I'm leaning towards the former option.
- What should happen if the
callable
doesn't return a uniquestring
orint
?- Ex: returns
null
orobject
, throws an exception, or returns a duplicate key? - IMO it should behave identically to that long
array_combine()
example I showed earlier.
- Ex: returns
- Is there any value in passing the current key as the second parameter to the
callable
?- I'm thinking no, since those values are being thrown out. If the need arises, this could always be added in a future PHP version.
- Which parameter should come first - the
array
or thecallable
? - Is this proposal even a good idea?
- I hope so :)
More on zend_parse_parameters()