Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete previous all elements from a specified index in PHP?

Tags:

arrays

php

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?

like image 621
w3outlook Avatar asked Mar 28 '19 08:03

w3outlook


People also ask

How do you remove an element from an array at a specific index?

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.

What does Array_splice () function do give an example?

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).

What is the function name in PHP used to delete an element from an array?

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.


Video Answer


2 Answers

$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

like image 55
Mikalai Halavach Avatar answered Sep 21 '22 05:09

Mikalai Halavach


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"
}
like image 43
Cid Avatar answered Sep 23 '22 05:09

Cid