Remove the Nth element from the end of an array

You can use the PHP array_splice() function Remove the Nth element from the end of an array. The array_splice() function remove elements from an array and replace it with new elements.The function also returns an array with the removed elements.

Read Also: Remove Last Element From An Array In PHP

Syntax

array_splice(array, start, length, array);

First let’s see the $colors array output :

<?php
$colors = array("yellow", "red", "green", "orange", "purple");
print_r($colors);
?>

Output:

Array
(
    [0] => yellow
    [1] => red
    [2] => green
    [3] => orange
    [4] => purple
)

Remove the Nth element from the end of an array

Now we will use PHP array_splice() function to remove the last two element of an array like in below example:

<?php
$colors = array("yellow", "red", "green", "orange", "purple");

// delete the last two element of an array
array_splice($colors, -2);
print_r($colors);
?>

Output:

Array
(
    [0] => yellow
    [1] => red
    [2] => green
)

This second start parameter refers to the starting position of the array from where the elements need to be removed. It is required to pass this numeric value. If the value supplied is negative, then the function starts removing from the end of the array, i.e., -2 means start at the second last element of the array.

If you want to remove the last element of an array then use below code:

<?php
$colors = array("yellow", "red", "green", "orange", "purple");

// delete the last element of an array
array_splice($colors, -1);
print_r($colors);
?>

Output:

Array
(
    [0] => yellow
    [1] => red
    [2] => green
    [3] => orange
)

Leave A Reply

Your email address will not be published.