PHP: How to remove the first/last element from an array

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

In PHP, arrays are one of the most important data types. They are used to store multiple values in a single variable. At times, you might need to remove the first or last element from an array for various reasons such as parsing data or managing queues. PHP provides several functions to accomplish this task efficiently.

In this tutorial, we explore how to remove the first or last element from an array with built-in PHP functions, complemented by various examples and use cases.

Removing the First Element

To remove the first element of an array, you can use the array_shift() function. This function shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won’t be touched.

$fruits = ['apple', 'banana', 'cherry'];
$removedElement = array_shift($fruits);
// Output: apple
print_r($fruits);
// Output: Array ( [0] => banana [1] => cherry )

It is worth mentioning that array_shift() can be expensive in terms of performance if used on large arrays, as it reindexes the array.

Removing the Last Element

For removing the last element from an array, PHP provides the array_pop() function. It pops and returns the last value of the array, shortening the array by one element.

$fruits = ['apple', 'banana', 'cherry'];
$removedElement = array_pop($fruits);
// Output: cherry
print_r($fruits);
// Output: Array ( [0] => apple [1] => banana )

Working with Associative Arrays

Both array_shift() and array_pop() work with associative arrays as well. For associative arrays, the key-value pairs are affected.

$person = ['name' => 'John', 'age' => 30, 'occupation' => 'Developer'];
$removedElement = array_shift($person);
// Output: John
print_r($person);
// Associative keys preserve
// Output: Array ( [age] => 30 [occupation] => Developer )

$removedElement = array_pop($person);
// Output: Developer
print_r($person);
// Output: Array ( [age] => 30 )

Preserving Keys when Removing Elements

Sometimes, you may want to remove the first or last element without reindexing numeric keys or affecting the keys in associative arrays. For that, one would have to take a more manual approach using functions like key(), reset(), end(), and unset().

// Removing the first element with keys preserved
$fruits = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
reset($fruits);
$firstKey = key($fruits);
unset($fruits[$firstKey]);
print_r($fruits);
// Output: Array ( [b] => banana [c] => cherry )

// Removing the last element with keys preserved
end($fruits);
$lastKey = key($fruits);
unset($fruits[$lastKey]);
print_r($fruits);
// Output: Array ( [b] => banana )

Advanced Manipulations

In some advanced scenarios, you might want to remove the first or last element based on specific conditions. You can iterate over the array with loops or use array functions such as array_filter() and array_slice() for such purposes.

Nested arrays or multidimensional arrays require additional consideration when removing their elements, often utilizing recursive functions or references.

// More advanced example with conditions
$numbers = [10, 20, 30, 40, 50];
$numbers = array_filter($numbers, function($value) {
    return $value <= 30; // Keep elements 30 or lower
});
print_r($numbers);
// Output: Array ( [0] => 10 [1] => 20 [2] => 30 )

Performance Considerations

Using functions such as array_shift() on large arrays can negatively impact performance as it has to reindex the array. When performance is critical, consider alternative methods such as creating a new array with the desired elements, if removing a large number of elements.

Conclusion

In PHP, the array_shift() and array_pop() functions are straightforward tools for removing the first or last element of an array. For situations requiring the preservation of keys or conditional removal, using other PHP functions or control structures can offer more control and efficiency. When working with arrays in PHP, always consider the impact on performance, especially with larger data structures.