简体   繁体   中英

How to delete previous all elements from a specified index in 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?

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

You can also use unset() to remove the elements. As shown below.

<?php

$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$index = 3;

for($i = 0; $i<$index; $i++) 
{   unset($array[$i]);  }

echo "<pre>";print_r($array);

?>

You can use array_slice :

$array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];
$newArray = array_slice($array, 3, NULL, TRUE);
echo '<pre>';
print_r($newArray);
echo '</pre>';

Output:

Array
(
    [3] => d
    [4] => e
)

Note that 4 th parameter: TRUE -> preserve_keys is very important.

If it is set to true, preserves the keys in the output array.

Your new array will now have all elements only after index 3

All elements before 3 are not returned here.

Try this

<?php

  $array = [0 => "a", 1 => "b", 2 => "c", 3=>"d", 4=>"e"];

  $new_array = array_slice($array, 3); // 3 is your key to slice

  print_r($new_array);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM