Remove first and last element from an array in PHP
In this post, we will see how to remove the first element from an array and return its value in PHP.
1. Removing last element using array_pop() function
The standard solution to remove the last element from an array is using the array_pop() function which return the value of the removed element. The time complexity of array_pop() is constant.
The following code pops the element off the end of the array using the array_slice() function, shortening the array by one element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $arr = [1, 2, 3, 4, 5]; $last = array_pop($arr); print_r("The last item is " . $last . "\n"); print_r($arr); /* Output: The last item is 5 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) */ ?> |
For associative arrays:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $arr = array("Nick"=>"20", "John"=>"10", "Paul"=>"18"); $last = array_pop($arr); print_r("The value of the last item is " . $last . "\n"); print_r($arr); /* Output: The value of the last item is 18 Array ( [Nick] => 20 [John] => 10 ) */ ?> |
2. Removing first element using array_shift() function
If you need to remove the first element from an array, you can use the array_shift() function which deletes and return the first element in the array. The time complexity of array_shift() is linear since it has to run over all the elements in order to re-index them.
The following code shifts an element off the beginning of the array using the array_slice() function, shortening the array by one element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $arr = [1, 2, 3, 4, 5]; $first = array_shift($arr); print_r("The first item is " . $first . "\n"); print_r($arr); /* Output: The first item is 1 Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 ) */ ?> |
For associative arrays:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $arr = array("Nick"=>"20", "John"=>"10", "Paul"=>"18"); $first = array_shift($arr); print_r("The value of the first item is " . $first . "\n"); print_r($arr); /* Output: The value of the first item is 20 Array ( [John] => 10 [Paul] => 18 ) */ ?> |
That’s all about removing the first and last element from an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)