Prompted by dire need, and inspired by some of the existing notes, I came up with this:
/* Like array_splice(), but preserves the key(s) of the replacement array. */
function array_splice_assoc(&$input, $offset, $length = 0, $replacement = array()) {
$tail = array_splice($input, $offset);
$extracted = array_splice($tail, 0, $length);
$input += $replacement + $tail;
return $extracted;
};
Apart from preserving the keys, it behaves just like the regular array_splice() for all cases I could think of.
So for example the regular array_splice()
$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);
will give:
Array
(
[c] => 3
[d] => 4
[e] => 5
)
Array
(
[a] => 1
[b] => 2
[0] => bar
[1] => baz
[f] => 6
)
But with array_splice_assoc()
$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice_assoc($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);
we get:
Array
(
[c] => 3
[d] => 4
[e] => 5
)
Array
(
[a] => 1
[b] => 2
[foo1] => bar
[foo2] => baz
[f] => 6
)
A typical use case would be replacing an element identified by a particular key, which we could achieve with:
$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
array_splice_assoc($input, array_search('d', array_keys($input)), 1, array('foo' => 'bar'));
print_r($input);
giving us:
Array
(
[a] => 1
[b] => 2
[c] => 3
[foo] => bar
[e] => 5
[f] => 6
)