note 115351 added to function.array-splice
| From: | antrik | Date: | Wed, 09 Jul 2014 19:20:59 +0000 |
| Subject: | note 115351 added to function.array-splice | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199905@lists.php.net to get a copy of this message | ||
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
)
----
Server IP: 216.194.115.244
Probable Submitter: 212.8.198.143
----
Manual Page -- http://php.net/manual/en/function.array-splice.php
Edit -- https://master.php.net/note/edit/115351
Del: integrated -- https://master.php.net/note/delete/115351/integrated
Del: useless -- https://master.php.net/note/delete/115351/useless
Del: bad code -- https://master.php.net/note/delete/115351/bad+code
Del: spam -- https://master.php.net/note/delete/115351/spam
Del: non-english -- https://master.php.net/note/delete/115351/non-english
Del: in docs -- https://master.php.net/note/delete/115351/in+docs
Del: other reasons-- https://master.php.net/note/delete/115351
Reject -- https://master.php.net/note/reject/115351
Search -- https://master.php.net/manage/user-notes.php