Hàm array_splice[]
xóa phần tử trong mảng và thay thế bằng một phần tử hoặc một số phần tử khác.
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.
Cú pháp
Cú pháp: array_splice[$array, $offset [, $lenght, $replace]];
Trong đó:
$array
là mảng dữ liệu truyền vào.$offset
là vị trí của phần tử đầu tiên bị xóa.
Các phần tử tron dấu [ ] có thể không truyền vào:
$lenght
là số phần tử bị xóa.$replace
phần tử hoặc mảng thay thế các phần tử bị xóa.
Ví dụ
$lenght
dương:
Bài viết này được đăng tại [free tuts .net]
Code
$input = range[0,10]; array_splice[$input, 5, 4, ["25","22"]]; echo ""; print_r[$input]; echo "";
Kết quả
Array [ [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 25 [6] => 22 [7] => 9 [8] => 10 ]
$lenght
âm:
Code
$input = range[0,10]; array_splice[$input, 2, -2]; echo ""; print_r[$input]; echo "";
Kết quả
Array [ [0] => 0 [1] => 1 [2] => 9 [3] => 10 ]
$lenght
= 0:
Code
$input = range[0,10]; array_splice[$input, 5, 0]; echo ""; print_r[$input]; echo "";
Kết quả
Array [ [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 ]
Tham khảo: php.net
Định nghĩa hàm array_splice[]
trong PHP
Hàm này gỡ bỏ các phần tử đã được chỉ định bởi tham số offset và length từ mảng input, và thay thế chúng bởi các phần tử trong mảng replacement, nếu được cung cấp. Nó trả về một mảng chứa các phần tử đã bị trích [bị gỡ].
Cú pháp hàm array_splice[]
trong PHP
Hàm array_splice[]
trong PHP có cú pháp như sau:
array_splice [ $input, $offset [,$length [,$replacement]] ];
Tham số
- input: Bắt buộc. Xác định một mảng
- offset: Bắt buộc. Giá trị số. Xác định nơi hàm bắt đầu việc gỡ bỏ phần tử. 0 = phần tử đầu tiên. Nếu giá trị này là số âm, thì hàm sẽ bắt đầu từ phần tử cuối cùng [-2 nghĩa là bắt đầu từ phần tử cuối cùng thứ hai của mảng]
- length: Tùy ý. Giá trị số. Xác định bao nhiêu phần tử bị gỡ bỏ, và nó cũng là length của mảng trả về. Nếu giá trị này là số âm, nó sẽ dừng ở phần tử cuối cùng. Nếu giá trị này không được thiết lập, nó sẽ gỡ bỏ tất cả phần tử, bắt đầu từ vị trí được xác định bởi start-parameter
- replacement: Tùy ý. Xác định một mảng với các phần tử mà sẽ được chèn vào mảng nguồn. Nếu nó chỉ là một phần tử, nó có thể là một chuỗi, không phải là một mảng
Trả về giá trị
Nó trả về value cuối của mảng, rút gọn mảng đi một phần tử.
Ví dụ minh họa cách sử dụng hàm array_splice[]
trong PHP:
Lưu chương trình trên trong một file có tên là test.php trong htdocs, sau đó mở trình duyệt và gõ địa chỉ //localhost:8080/test.php sẽ cho kết quả:
Xem thêm Hàm trong php
[PHP 4, PHP 5, PHP 7, PHP 8] array_splice — Remove a portion of the array and replace it with something else array_splice[ Note: Numerical keys in Note: If The input array. If If If If If If Tip To remove everything from If If Note: Keys in the If Returns an array consisting of the extracted elements. Example #1 array_splice[] examplesDescription
array &$array
,
int $offset
,
?int $length
=
null
,
mixed $replacement
= []
]: arrayarray
are not preserved. replacement
is not an array, it will be typecast to one [i.e. [array] $replacement
]. This may result in unexpected behavior when using an object or null
replacement
. Parameters
array
offset
offset
is positive then the start of the removed portion is at that offset from the beginning of the array
array. offset
is negative then the start of the removed portion is at that offset from the end of the array
array. length
length
is omitted, removes everything from offset
to the end of the array. length
is specified and is positive, then that many elements
will be removed. length
is specified and is negative, then the end of the removed portion will be that many elements from the end of the array. length
is specified and is zero, no elements will be removed. offset
to the end of the array when replacement
is also specified, use count[$input]
for length
. replacement
replacement
array is specified, then the removed elements are replaced with elements from this
array. offset
and length
are such that nothing is removed, then the elements from the replacement
array are inserted in the place specified by the offset
. replacement
array are not preserved. replacement
is just one element it is not necessary to put array[]
or square brackets around it, unless the element is an array itself, an object or null
. Return
Values
Changelog
VersionDescription 8.0.0
length
is nullable now.
Examples
The above example will output:
array[2] { [0]=> string[3] "red" [1]=> string[5] "green" } array[2] { [0]=> string[3] "red" [1]=> string[6] "yellow" } array[2] { [0]=> string[3] "red" [1]=> string[6] "orange" } array[5] { [0]=> string[3] "red" [1]=> string[5] "green" [2]=> string[4] "blue" [3]=> string[5] "black" [4]=> string[6] "maroon" }
Example #2 Equivalent statements to various array_splice[] examples
The following statements are equivalent:
See Also
- array_merge[] - Merge one or more arrays
- array_slice[] - Extract a slice of the array
- unset[] - Unset a given variable
StanE ¶
6 years ago
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].
mrsohailkhan at gmail dot com ¶
10 years ago
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'
daniele centamore ¶
13 years ago
just useful functions to move an element using array_splice.
royanee at yahoo dot com ¶
9 years ago
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.
gilberg_vrn ¶
6 years ago
array_splice with preserve keys
Example:
charette dot s at gmail ¶
12 years ago
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
]
gideon at i6developments dot com ¶
18 years ago
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:
weikard at gmx dot de ¶
16 years ago
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.
kbrown at horizon dot sk dot ca ¶
19 years ago
[ Editor's Note: If you're not concerned with the indexes being contiguously numbered [such as for an associative array] then unset[$ar[$ind]]; will accomplish the same as the code below without requiring splice/splice/merge. If contiguous numbering IS a concern [such as for indexed arrays], you can still save time by using: unset[$ar[$ind]]; $ar = array_values[$ar]; ]
Removing elements from arrays
This works better - much quicker
plintus at smtp dot ru ¶
19 years ago
key-safe:
smth like this. hope you like it more than versions above :]
news_yodpeirs at thoftware dot de ¶
12 years ago
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
csaba at alum dot mit dot edu ¶
17 years ago
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
guillaume dot lacourt at gmail dot com ¶
7 years ago
Using array_splice when you traverse array with internal pointer's function reset the array, eg:
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.
jrhardytwothousandtwo at yahoo dot com ¶
20 years ago
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.
$returned should be an empty array as nothing was returned. This would have substance if you were doing a replace instead.
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.
dead dot screamer at seznam dot cz ¶
13 years ago
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]
}
pauljamescampbell at gmail dot com ¶
14 years ago
Here's my own take on an array slice method that preserves keys from an associative array.
ahigerd at stratitec dot com ¶
15 years ago
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
Paul ¶
16 years ago
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].
Anonymous ¶
20 years ago
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];
paule at cs dot tamu dot edu ¶
20 years ago
to :
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.
paule at cs dot tamu dot edu ¶
20 years ago
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.
mip at ycn dot com ¶
15 years ago
Ever wounder what array_splice is doing to your references, then try this little script and see the output.
array[5] { So array_splice is reference safe, but you have to be careful about the generation of the replacement array. have fun, cheers!
The output will be [PHP 4.3.3]:
[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?"
bdjumakov at gmail dot com ¶
16 years ago
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.
kokos at lac dot lviv dot ua ¶
20 years ago
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.
Anonymous ¶
1 year ago
the following:
$input = [[5=>"richard=red"], [15=>"york=yellow"], [25=>"gave=green"], [30=>"battle=blue"], [35=>"in=indigo"], [40=>"vain=violet"]];
array_splice[$input, 2, 0, [[10=>"of=orange"]]];
var_dump[$input];
gives this:
array [size=7]
0 =>
array [size=1]
5 => string 'richard=red' [length=11]
1 =>
array [size=1]
15 => string 'york=yellow' [length=11]
2 =>
array [size=1]
10 => string 'of=orange' [length=9]
3 =>
array [size=1]
25 => string 'gave=green' [length=10]
4 =>
array [size=1]
30 => string 'battle=blue' [length=11]
5 =>
array [size=1]
35 => string 'in=indigo' [length=9]
6 =>
array [size=1]
40 => string 'vain=violet' [length=11]
vitospericolato at gmail dot com ¶
6 years ago
To remove elements from an array, based on array values:
Hayley Watson ¶
4 years ago
For an analogous function that works on strings rather than arrays, see substr_replace.
randomdestination at gmail dot com ¶
17 years ago
To split an associative array based on it's keys, use this function:
Array Hope this helps anyone!
Example:
Will print:
[
[d] => 4
]
Array
[
[a] => 1
[b] => 2
[c] => 3
]
antrik ¶
8 years ago
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
]
news_yodpeirs at thoftware dot de ¶
11 years ago
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].
madmax at max-worlds dot net ¶
13 years ago
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.