百科狗-知识改变命运!
--

array_splice() - 去掉数组中的某一部分并用其它值取代 - php 数组函数

乐乐1年前 (2023-11-21)阅读数 22#技术干货
文章标签数组

array_splice()

(PHP 4, PHP 5, PHP 7)

去掉数组中的某一部分并用其它值取代

说明

array_splice(array &$input,int $offset[,int $length= count($input)[,mixed $replacement= array()]]): array

把$input数组中由$offset和$length指定的单元去掉,如果提供了$replacement参数,则用其中的单元取代。

注意$input中的数字键名不被保留。

Note:如果$replacement不是数组,会被类型转换成数组(例如:(array)$replacement)。当传入的$replacement是个对象或者NULL,会导致未知的行为出现。

参数

$input

array_splice() - 去掉数组中的某一部分并用其它值取代 - php 数组函数

输入的数组。

$offset

如果$offset为正,则从$input数组中该值指定的偏移量开始移除。如果$offset为负,则从$input末尾倒数该值指定的偏移量开始移除。

$length

如果省略$length,则移除数组中从$offset到结尾的所有部分。如果指定了$length并且为正值,则移除这么多单元。如果指定了$length并且为负值,则移除从$offset到数组末尾倒数$length为止中间所有的单元。如果设置了$length为零,不会移除单元。小窍门:当给出了$replacement时要移除从$offset到数组末尾所有单元时,用count($input)作为$length。

$replacement

如果给出了$replacement数组,则被移除的单元被此数组中的单元替代。

如果$offset和$length的组合结果是不会移除任何值,则$replacement数组中的单元将被插入到$offset指定的位置。注意替换数组中的键名不保留。

如果用来替换$replacement只有一个单元,那么不需要给它加上array(),除非该单元本身就是一个数组、一个对象或者NULL

返回值

返回一个包含有被移除单元的数组。

范例

Example #1array_splice()例子

Example #2array_splice()例子

以下表达式以同样方式修改了$input:

参见

  • array_slice() 从数组中取出一段
  • unset() 释放给定的变量
  • array_merge() 合并一个或多个数组
array_splice, split an array into 2 arrays. The returned arrays is the 2nd argument actually and the used array e.g $input here contains the 1st argument of array, e.g

if you want to replace any array value do simple like that,
first search the array index you want to replace

and then use it as according to the definition

so here green is replaced by mygreen.
here 1 in array_splice above represent the number of items to be replaced. so here start at index '1' and replaced only one item which is 'green'
When trying to splice an associative array into another, array_splice is missing two key ingredients:
 - a string key for identifying the offset
 - the ability to preserve keys in the replacement array
This is primarily useful when you want to replace an item in an array with another item, but want to maintain the ordering of the array without rebuilding the array one entry at a time.

Note: I have not tested this with negative offsets and lengths.
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".

[RESULT]
Array (
  [row1] => Array (
      [col1] => foobar!
      [col2] => foobar!
    )
  [row2] => Array (
      [col1] => foobar!
      [col2] => foobar!
    )
  [0] => Array (
      [colX] => foobar2
    )
  [row3] => Array (
      [col1] => foobar!
      [col2] => foobar!
    )
)
But you can use the following function:
function array_insert (&$array, $position, $insert_array) {
 $first_array = array_splice ($array, 0, $position);
 $array = array_merge ($first_array, $insert_array, $array);
}

[RESULT]
Array (
  [row1] => Array (
      [col1] => foobar!
      [col2] => foobar!
    )
  [row2] => Array (
      [col1] => foobar!
      [col2] => foobar!
    )
  [rowX] => Array (
      [colX] => foobar2
    )
  [row3] => Array (
      [col1] => foobar!
      [col2] => foobar!
    )
)
[NOTE]
The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.
Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time. The last two methods took significantly more time than the first two. The most surprising lesson is that using the & incurs a time hit.

Csaba Gabor from Vienna
just useful functions to move an element using array_splice. 
Splicing with NULL as replacement may result in unexpected behavior too. Typecasting NULL into an array results in an empty array (as "(array)NULL" equals "array()"). That means, instead of creating an element with value NULL just no new element ist created (just as if there was no replacement specified).
If you want the splicing to create a new element with value NULL you have to use "array(NULL)" instead of NULL.
You should expect this if you read the explanation carefully, but just as objects are considered as a special case for replacement, NULL should be too.
The explanation of replacement better should read: "If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL."
And the note better should be: "If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement."
jmtc
If you want to append null values wrap them in an array:

Array
(
  [0] => Hey
  [1] => hey
  [2] => my
  [3] => my
)

Array
(
  [0] => Hey
  [1] => 
  [2] => hey
  [3] => my
  [4] => my
)
array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically. 
Code: 
key-safe:

smth like this. hope you like it more than versions above :)
A reference is made to INSERT'ing into an array here with array_splice, however its not explained very well. I hope this example will help others find what took me days to research.

Remember that you are telling the array to insert the element into the KEY position. Thus the elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5. And walla, you've inserted. I can't say if this is of any value for named keys, or multidimensional arrays. However it does work for single dimensional arrays.
$returned should be an empty array as nothing was returned. This would have substance if you were doing a replace instead.
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array. 
Sometimes you may want to insert one array into another and just work on with the resulting array. array_splice() doesn't support this, as the resulting array isn't the returned value but the first argument, which is changed by reference.
Therefore you may use the following function, which inserts array $ins in array $src at position $pos. $rep can be used if $ins shouldn't be just inserted, but should replace some existing elements (the number of elements to be replaced is given in $rep). 
In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.
In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).
to kokos@lac.lviv.ua:
Good point about the code not doing what you expected.
The failure to check for the insert case like you pointed out is not a bug, however. I didn't add code to handle that because the key of such an added index is more or less undefined in an unordered associative array. Put another way, if your array is associative and not auto-indexed, you most likely care enough about your keys to want to set them explicitly.
After reading KoKos' post above, I thought that the code I posted right before his should do what he wanted. However, my original post neglected to note the little "Tip" in the documentation above, about a single element replacement.
If one changes the lines in my code above that says:

to instead say:

that will solve the problem.
Sorry for the omission.
It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...
Contrary to the equivalence noted on this page
$input[$x] = $y    array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected, 
even provided that you have only INTEGER keys!
The following code:
  $t=array('a','b','c','d','e');
  var_dump($t);

Will produce:
array(5) {
 [0]=>
 string(1) "a"
 [1]=>
 string(1) "b"
 [2]=>
 string(1) "c"
 [3]=>
 string(1) "d"
 [4]=>
 string(1) "e"
}
array(3) {
 [2]=>
 string(1) "c"
 [4]=>
 string(1) "e"
 [0]=>
 string(1) "f"
}
array(3) {
 [0]=>
 string(1) "g"
 [1]=>
 string(1) "e"
 [2]=>
 string(1) "f"
}
Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_. :)
I think that "equivalence note" should be considered buggy. ;)))
Best wishes.
KoKos.
array_splice with preserve keys

Example: 
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:

Example:

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).
For an analogous function that works on strings rather than arrays, see substr_replace.
To remove elements from an array, based on array values: 
Using array_splice when you traverse array with internal pointer's function reset the array, eg: 
Maybe it will help someone else: I was trying to strip off the last part of an array using this section, more or less as follows:

Now it could occur in my code that , in which case the array is returned as-is and not, as you might expect, an empty array because everything is stripped off. Obviously it is not really useful anyway to "strip off everything", but I was reminded of that the hard way and this may spare someone some time, hopefully.
To split an associative array based on it's keys, use this function:

Example: 

Will print:
Array
(
  [d] => 4
)
Array
(
  [a] => 1
  [b] => 2
  [c] => 3
)
Hope this helps anyone!
Here's my own take on an array slice method that preserves keys from an associative array. 
Ever wounder what array_splice is doing to your references, then try this little script and see the output.

The output will be (PHP 4.3.3):
array(5) {
 [0]=>
 &string(4) "test"
 [1]=>
 &string(10) "this be d?"
 [2]=>
 string(13) "or this be d?"
 [3]=>
 &string(5) "test2"
 [4]=>
 &string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"
So array_splice is reference safe, but you have to be careful about the generation of the replacement array.
have fun, cheers!
I need  function, that use array keys instead of order (offset and length) because of associated arrays, and this is result:

Both examples output:
array(11) {
 [0]=>
 int(1)
 [1]=>
 int(2)
 [2]=>
 int(3)
 [100]=>
 int(101)
 [101]=>
 int(102)
 [102]=>
 int(103)
 [103]=>
 int(104)
 [6]=>
 int(7)
 [7]=>
 int(8)
 [8]=>
 int(9)
 [9]=>
 int(10)
}
Please note that array_splice() 's second argument is an OFFSET and not an INDEX.
Lets say you want to 
$array_of_items = array ('nothing','myitem','hisitem','heritem');
$sid = array_search('myitem',$array_of_items);
echo $sid; /* prints out 1, since index element 1 is "myitem" */
Now, lets say we want to remove that "myitem" from the array:

Notice how you have to add a one to the $sid variable? That is because offset item 1 is "nothing" and since $sid is currently 1 (the index of "myitem"), we add 1 more to it to find out
 its OFFSET.
DO NOT DO THIS:
 $array_of_items = array_splice($array_of_items,$sid,1);
Note: If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object replacement . 
Example :

Outputs :
Array : Array
{
  [0] => foo
  [1] => bar
}
Solution : Enforce the array() on the object.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)