I have an array and I want to delete previous all elements from the current specified index
For example:
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
I have an index like 3
, so I want to delete previous all like
0 => "a", 1 => "b", 2 => "c"
and only have
3=>"d", 4=>"e"
in my new array. Can anyone help me?
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array.
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$output = array_slice($array, 3);
output:
array(2) {
[0]=> string(1) "d"
[1]=> string(1) "e"
}
Another solution with saving index
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$output = array_slice($array, 3, null, true);
output:
array(2) {
[3]=> string(1) "d"
[4]=> string(1) "e"
}
https://www.php.net/manual/en/function.array-slice.php
You may to use array_slice()
In example :
<?php
$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$startingPosition = 3;
// Preserve keys
// |
// Your array Delete from Delete to |
// | | (if null, |
// | | to the end) |
// | | | |
// v v v v
$array = array_slice($array, $startingPosition , null, true);
var_dump($array);
Output :
array(2) {
[3]=>
string(1) "d"
[4]=>
string(1) "e"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With