note 118184 added to function.array-splice
| From: | StanE | Date: | Thu, 22 Oct 2015 08:50:48 +0000 |
| Subject: | note 118184 added to function.array-splice | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-204002@lists.php.net to get a copy of this message | ||
array_splice() does not preserve numeric keys. The function posted by "weikard at gmx dot
de" won't do that either because array_merge() does not preserve numeric keys either.
Use following function instead:
<?php
function arrayInsert($array, $position, $insertArray)
{
$ret = [];
if ($position == count($array)) {
$ret = $array + $insertArray;
}
else {
$i = 0;
foreach ($array as $key => $value) {
if ($position == $i++) {
$ret += $insertArray;
}
$ret[$key] = $value;
}
}
return $ret;
}
?>
Example:
<?php
$a = [
295 => "Hello",
58 => "world",
];
$a = arrayInsert($a, 1, [123 => "little"]);
/*
Output:
Array
(
[295] => Hello
[123] => little
[58] => world
)
*/
?>
It preserves numeric keys. Note that the function does not use a reference to the original array but
returns a new array (I see absolutely no reason how the performance would be increased by using a
reference when modifying an array through PHP script code).
----
Server IP: 72.52.91.14
Probable Submitter: 85.177.91.112
----
Manual Page -- http://php.net/manual/en/function.array-splice.php
Edit -- https://master.php.net/note/edit/118184
Del: integrated -- https://master.php.net/note/delete/118184/integrated
Del: useless -- https://master.php.net/note/delete/118184/useless
Del: bad code -- https://master.php.net/note/delete/118184/bad+code
Del: spam -- https://master.php.net/note/delete/118184/spam
Del: non-english -- https://master.php.net/note/delete/118184/non-english
Del: in docs -- https://master.php.net/note/delete/118184/in+docs
Del: other reasons-- https://master.php.net/note/delete/118184
Reject -- https://master.php.net/note/reject/118184
Search -- https://master.php.net/manage/user-notes.php