Array_splice acting as array_slice?
I'm having issues understanding exactly what array_splice and array_slice do. From what I can tell array_splice should return an array AFTER taking out certain elements and array_slice should retrieve a slice of the array.
The following code from the php.net/array_splice manual shows that this code should work.
$input = array("red", "green", "blue", "yellow");
var_dump(array_splice($input, 2));
// $input is now array("red", "green")
$input = array("red", "green", "blue", "yellow");
var_dump(array_slice($input, 2));
// $input is now array("red", "green")
However when I run this code on php 5.3.4 and 5.1.6 the results are
array
0 => string 'blue' (length=4)
1 => string 'yellow' (length=6)
array
0 => string 'blue' (length=4)
1 => string 'yellow' (length=6)
Am I misunderstanding the manual or is this a bug? It looks to me like array_splice is acting just like array_slice
Also it does not seem to do replacements
$input = array("red", "green", "blue", "yellow");
var_dump(array_splice($input, 2, 2, array('foo')));
outputs
array
0 => string 'blue' (length=4)
1 => string 'yellow' (length=6)
Can someone confirm this is a bug and if not explain how this SHOULD work?
EDIT:
Nvm I figured it out. Instead of using a var_dump on the array_splice I should be using $input as array_splice changes $input instead of returning the ne开发者_Go百科w values.
array_slice returns the values while array_splice sets the values to $input.
MODs please close or delete this.
From the docs:
Description
array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] )Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.
...
Return Values
Returns the array consisting of the extracted elements.
You are just horribly, horribly confused.
splice removes a subset of array elements and inserts new elements in their location basically replacing them. slice just pulls a subset of array elements into a separate array.
Where you are misunderstanding is that the result of slice is returned from the function as a separate array, where splice actually manipulates the array that is passed in as the argument.
In your first code example the comment state that what is left in the variable $input
is array("red", "green")
but makes no mention of the content returned by the var_dump
which is what your tryouts returns
精彩评论