Remove Last element from an array in PHP

You can use the PHP array_pop() function remove last element from an array in PHP. The array_pop() function returns the last value of the array. If array is empty or is not an array then NULL will be returned.

Read Also: How to Remove the First element from an array in PHP

First let’s see the $stack array output :

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

Output:

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

$stack array have 5 elements and we want to remove the last element has value “purple”.

Remove Last element from an array

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

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

// delete the last element of an array
$removed = array_pop($stack);
print_r($stack);
?>

Output:

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

and purple will be assigned to $removed.

<?php
echo $removed;
?>

Output:

purple

Leave A Reply

Your email address will not be published.