I need to delete the first 29 values of an arra开发者_如何转开发y. I searched and there doesn't seem to be any built in PHP function that allows for this. How can this be done then?
array_splice($array, 0, 29);
array_splice
deletes the elements from the array and returns the deleted elements.
Alternatively, if you want to keep the original array, but want to create a new array with the first 29 elements removed, use array_slice
:
$newArray = array_slice($array, 29);
You can use array_splice
to remove values from an array:
array_splice($arr, 0, 29)
The array is passed as a reference as array_splice
modifies the array itself. It returns an array of the values that have been removed.
Here’s an example for how it works:
$arr = range(1, 30);
$removed = array_splice($arr, 0, 29);
var_dump($arr); // array(1) { [0]=> int(30) }
var_dump($removed); // array(29) { [0]=> int(1) … [28]=> int(29) }
In opposite to that, array_slice
(without p) just copies a part of an array without modifying it:
$arr = range(1, 30);
$copied = array_slice($arr, 29);
var_dump($arr); // array(30) { [0]=> int(1) … [29]=> int(30) }
var_dump($copied); // array(1) { [0]=> int(30) }
Here array_slice($arr, 29)
copies everything from the offset 29 on up to the end while leaving the $arr
as is.
But as you said you want to delete values, array_splice
seems to be the better choice instead of copying a part and re-assigning the copied part back to the variable like this:
$arr = array_slice($arr, 29);
Because although this has the same effect (first 29 values are no longer there), you do the copy operation twice: create a new array and copy everything except the first 29 values and then re-assign that value to $arr
(requires copying the whole array again).
精彩评论