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

$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"
}

You can use veriation of array-slice and so on (as array_slice($array, 3) ) but also simple for loop:

$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$copy = false;
foreach($array as $k => $v) {
    $copy |= ($k == 3);
    if ($copy)
        $res[$k] = $v;
}

Tags:

Php

Arrays