Open In App

Remove an Elements From End of an Array in PHP

Last Updated : 31 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an array "myArray", the task is to remove an element from its end. This operation is important in scenarios involving stacks, queues, and web development. In PHP, there are several approaches to achieve this One common method is using the array_pop() function, which removes the last element from the array. For instance, if "myArray" initially contains string elements and we apply array_pop() to remove 'date' from its end, the modified array can be displayed using "print_r($myArray)", showcasing the updated contents without 'date'.

Example:

Input: $myArray = ["apple", "banana", "cherry", "date"];
Output: ["apple", "banana", "cherry"];

These are the following approaches:

Using the unset() function with the last index

We are going to use the unset() function in the PHP arrays which are the ordered maps and use the integer keys starting from 0. To remove an element from the end of an array using unset(), we specify the index of the last element in the array.

Example: To demonstrate removing an element from the end of the array using unset() function in PHP.

<?php
$array = [1, 2, 3, 4, 5];
echo "Original array: " . implode(", ", $array) . "\n";

$lastIndex = count($array) - 1;
unset($array[$lastIndex]);

echo "Modified array: " . implode(", ", $array) . "\n";
?>

Output
Original array: 1, 2, 3, 4, 5
Modified array: 1, 2, 3, 4

Using the array_pop() function

We are going to use the array_pop() function that is used to remove the last element from an array and returns the removed element.

Example: To demonstrate removing an element from the end of the array using arrya_pop() function in PHP.

<?php
$array = [1, 2, 3, 4, 5];
echo "Original array: " . implode(", ", $array) . "\n";

$removedElement = array_pop($array);

echo "Modified array: " . implode(", ", $array) . "\n";
echo "Removed element: " . $removedElement . "\n";
?>

Output
Original array: 1, 2, 3, 4, 5
Modified array: 1, 2, 3, 4
Removed element: 5

Using the array_slice() function

We are going to use the array_slice() function which returns a sequence of elements from the array, defined by the offset and length parameters. By slicing the array from the beginning to the second-to-last element, we effectively remove the last element.

Example: Removing an element from the end of the array using array_slice() function in PHP.

<?php
$array = [1, 2, 3, 4, 5];
echo "Original array: " . implode(", ", $array) . "\n";

$modifiedArray = array_slice($array, 0, -1);

echo "Modified array: " . implode(", ", $modifiedArray) . "\n";
?>

Output
Original array: 1, 2, 3, 4, 5
Modified array: 1, 2, 3, 4


Similar Reads

three90RightbarBannerImg