Suppose I have this associative array:
$fruits = array(
'red' => 'strawberry',
'blue' => 'banana',
'green' => 'apple',
);
I want to change the key blue
into yellow
. Note that I want to change a key, not a value. I could do this:
$fruits['yellow'] = $fruits['blue'];
unset($fruits['blue']);
But this results in 'yellow' => 'banana'
being at the end of the array. If I'd need to maintain the order of the array, so 'yellow' => 'banana'
is at the same position as 'blue' => 'banana'
was before, how do I do that?
Of course I can reconstruct the entire array, adding all key/value pairs and just inserting the yellow
instead of blue
key, but that seems a rather sluggish way of doing this.
Is there a smarter / more efficient (preferably PHP native) approach to it, to do this in-place?