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.

Download  Run Code

 
For associative arrays:

Download  Run Code

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.

Download  Run Code

 
For associative arrays:

Download  Run Code

That’s all about removing the first and last element from an array in PHP.