Recently I was working on something that required inserting key-value pairs into an array after a specific key in PHP. As I was looking through stackoverflow answers I realized that there was no awesome answer that really jumped out at me. Therefore I decided to take a few minutes to just write my own
array_splice_assoc() function to get the job done:
As you can see this function takes the same parameters that
array_splice() does but the difference is that the offset can be a string in this key which refers to the key after which the new array elements should be inserted.
One important thing to note is that if you try to insert a key-value pair in which the key exists before or at the offset, your key-value pair will not be inserted. On the other hand if you try to insert a key-value pair in which the key exists after offset, your value will replace the previous one.
Have fun! 😎