How does array_pop work in PHP

How does array pop work in php

The array_pop function, one of many different array-based functions in PHP is a common way to extract an element off the end of an array. A useful function that modifies the original array as it goes, which is great for when you are looking to build something similar to undo/redo functionality or stack operations. In this array_pop tutorial, we'll explore how the function works, how it can be applied to associative arrays, including how it can be used in combination with other PHP functions, such as array_shift.

array_pop

Array pop or array_pop() as it will be typically written in PHP code takes an array of data and returns back the last item in the array, whilst removing it from the array itself, therefore shortening the array by one element. If you had 5 elements before array_pop was used, afterward you'd have 4 elements. It's also possible to pop the last item of an array and run the (empty) array back through array_pop in which case would result in "null" getting returned. The basic syntax of array_pop is as follows, taking one parameter and returning a mixed set of data.

array_pop(array &$array): mixed

Let's explore how array_pop works and what it does with a basic usage example. Here we're passing an array into array pop in the following code "array_pop($array)" which will output the last colour in the list. Doing so will also remove that colour from the stack, leaving just red and green in the array.

$array = ["red", "green", "blue"];
$lastColour = array_pop($array);

echo $lastColour;
# Outputs
blue

print_r($array);
# Outputs
["red", "green"]

By popping an element off the bottom of the array, the array_pop function will use the reset() function to amend the array pointer. When passing an empty array to array_pop, the function will return null, as seen in the below PHP example.

array_pop([]);

# returns null

How to remove the first element of an array

It's possible to remove the first element of an array instead of the last by using the array_shift function instead of array_pop. As we know the array_pop function removes the last element, and array_shift removes the first element. Taking the following PHP example, with a simple array of numbers, we can see that array_shift removes the first, which is the number 1, whilst array_pop has removed the last, which is number 5.

$numbers = [1, 2, 3, 4, 5];
$firstNumber = array_shift($numbers);
$lastNumber = array_pop($numbers);

echo $firstNumber; // Outputs 1
echo $lastNumber; // Outputs 5

Array Pop and Associative Arrays

You don't have to work with just simple arrays in PHP when used with array_pop, it's possible to pass associative arrays too. Associative arrays are ones that it's keys are strings instead of numbers. Let's explore how it works, and what output we'd likely get. Our user array is made up of different keys "name", and "email". This time when we pass it through array_pop we'll get the array value of the element removed. That's the same behavior as a non-associative array, where it's common to expect the key value, (email in this case), but that's not how array_pop is designed to work. Array pop will always return the value and not the key that was removed. If we subsequently output the array using the print_r function our array with the string key names is still intact, barring one less element (the popped item has been removed).

$user = [
 "name" => "Foo Bar",
 "email" => "[email protected]",
];

$lastValue = array_pop($user);

echo $lastValue; // Outputs [email protected]
print_r($user); // Output: ["name" => "Foo Bar"]

How array_pop works with multidimensional arrays

A great feature of array_pop is that it can also handle multidimensional arrays. These types of arrays are typically more common in web applications, as they allow you to store more information in logical groups. When array pop encounters a multidimensional array it will treat the popping the same way by removing the last element, but because each element of a multidimensional array has nested arrays, the nested array will be removed as well. Let's explore a PHP example in practice to learn how this works.

Let's upgrade our previous user array to an array of users, each with a name and email. Once passed to the array_pop function the last element of the user's array will be removed. Because it's a nested array we cannot simply echo it back like our previous examples due to the fact that it's an array and not a string. That's because otherwise, we could attempt to perform an array-to-string conversion, and wouldn't get the desired result. Instead, we can use the print_r function in PHP to safely output the array content. Typically, print_r is best for when debugging (but you can also use var_dump to aid debugging), however, if you are looking to print something to screen, you'll need to ensure you print a string from array_pop.

$users = [
 [
 "name" => "Foo Bar",
 "email" => "[email protected]",
 ],
 [
 "name" => "John Doe",
 "email" => "[email protected]",
 ]
];

$lastValue = array_pop($users);
print_r($last);

Common array_pop errors

When working with the array_pop function there are numerous ways PHP will trigger warnings or fatal errors. Let's explore what they could be and how to overcome them. First up is array_pop's expected parameter, an array.

The first example when passing nothing will cause the PHP engine to trigger a fatal error to explain that PHP expected one argument, but 0 was provided.

# Triggers ArgumentCountError: array_pop() expects exactly 1 argument, 0 given
array_pop();

Another error that could be triggered is when passing a null or blank array into the function. Both cause PHP to trigger an error that outlines that the argument (which is expected to be an array), cannot be passed by reference. This refers to a variable that is being passed to a function or method in a way that allows the function itself to modify directly, rather than working on a copy of it. PHP triggers an error like this when the core PHP development team thinks that letting PHP modify data like this directly might cause undesired side effects and confusion among developers.

# Uncaught Error: array_pop(): Argument #1 ($array) cannot be passed by reference
array_pop(null);
array_pop([]);

Finally, and similar to the above, passing a variable where its contents are null. Here we are passing a variable "blank" to array_pop but have not defined it anywhere else, so, therefore, is null.

# Triggers array_pop() expects parameter 1 to be array, null given
array_pop($blank);

PHP array_pop more than one element

You might have a situation where you're required to pop more than one element off the array. For this, it's best to wrap the array_pop method in a while loop. Here you would be looking to loop around as many times as required. The following is an example of using a while loop and array_pop to remove more than one element from the array, where we have set the total number of "pops" to three. This means the code will loop three times, each time removing one element off the array, before being left with an array that contains elements 1, and 2.

$numbers = [1, 2, 3, 4, 5];
$numberOfPops = 3;

while ($numberOfPops > 0 && !empty($numbers)) {
 array_pop($numbers);
 $numberOfPops--;
}

print_r($numbers);

# Outputs
Array
(
 [0] => 1
 [1] => 2
)

Conclusion

Getting familiar with how array_pop works is a great way to become a next-level PHP programmer. Array pop offers a quick and easy way to remove the last element of your array, whilst PHP remembers which item that was should you require to use it.

  • Always pass a variable of type array to array_pop
  • Associated or multidimensional arrays are allowed
  • Remember the last item will always be removed from the input array you provide
  • Watch out for echoing the result to your user, especially when using multidimensional arrays, as they are nested

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Related Dev Guides

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all