array_splice() for associative arrays

arrays, php

Solution

I think you need to do that manually:

# Insert at offset 2
$offset = 2;
$newArray = array_slice($oldArray, 0, $offset, true) +
            array('texture' => 'bumpy') +
            array_slice($oldArray, $offset, NULL, true);

Problem

Say I have an associative array: ``` array( "color" => "red", "taste" => "sweet", "season" => "summer" ); ``` and I want to introduce a new element into it: ``` "texture" => "bumpy" ``` behind the 2nd item but preserving all the array keys: ``` array( "color" => "red", "taste" => "sweet", "texture" => "bumpy", "season" => "summer" ); ``` is there a function to do that? `array_splice()` won't cut it, it can work with numeric keys only.

Original source