PHP array_pop Function | Remove Elements From Array

PHP array_pop Function is an inbuilt function in PHP which removes the last element from an array. It returns the last value of the array. Also, it decrements the size of the array by one. PHP array_pop Function works opposite to array_push function.

Syntax

array_pop ( array $array );

Parameters

PHP array_pop Function takes in only one parameter.

$array: The required array from which the element needs to be removed.

If you don’t pass any parameter, PHP array_pop Function throws a Warning. However, it does not throw any warning/notice on passing an empty array.

Return Value

PHP array_pop Function returns the last element of the array. The returned element is removed from the array. If the array is empty, then it returns NULL.

PHP array_pop Function diagram

Examples

Let’s discuss a few examples to demonstrate the working of PHP array_pop Function.

Example 1

<?php
	
	$fruits = array('apple', 'mango', 'banana', 'melon');
	$poppedFruit = array_pop($fruits);
	print_r($poppedFruit);
	//melon

	print_r($fruits);
	/*
	Array
	(
    	[0] => apple
    	[1] => mango
    	[2] => banana
	)
	*/
?>

The above example shows a simple working of array_pop Function. An array is initialized with four elements. The PHP array_pop pops the last element from the array and returns it. Finally, there are three elements remaining in the array.

Example 2: Blank Array

For instance, consider an example passing an empty array.

<?php
	
	$fruits = array();
	$poppedFruit = array_pop($fruits);
	var_dump($poppedFruit);
	//NULL
?>

If an empty array is passed then the function returns NULL value.

Example 3: Looping through all elements

<?php
	
	$testArray = array('mango', 'apple', 'melon', 'grapes');
	while($poppedElement = array_pop($testArray)) {
		//do some logic
	}
	var_dump($testArray);
	/*
	array(0) { }
	*/
?>

You can loop through all elements in an array. In the example above, the while loop will iterate until all the elements are popped. In the end, the original array will become empty.

Conclusion

In conclusion, we learned about PHP array_pop Function. It can be used to remove the last element from the array. You may go through the Official Documentation to know more about the function. Additionally, feel free to explore other PHP Array Functions.

Please leave your valuable comments to help me improve this resource. Hope you found this article interesting.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *