Is it possible to insert a new key-value pair into a specific position in an associative array?
For example, let's say we have:
$array = [
'a' => 2,
'c' => 7,
];
$array['b'] = 5;
var_dump($array); // ['a' => 2, 'c' => 7, 'b' => 5]
I would like the new key b
to be inserted before c
. I know I can use ksort
to sort the keys alphabetically in this case after adding the new value. But as I do a lot of insert operations in this array, I don't want to sort all the keys every time I push a new key into the array.
So I'm trying to find a way to insert the value directly into the position I want, but I haven't found at the moment any built-in function to do that. It would be something like array_splice
but for associative arrays. Maybe it doesn't even exist.