How to remove last element from an array in PHP?

To remove the last element or value from an array, array_pop() function is used. This function returns the last removed element of the array and returns NULL if the array is empty, or is not an array. After removing the last element from the array, the array is modified, and the index is reduced by one from last, only if the keys are numerical.

It is an inbuilt array function of PHP, which deletes the last element of an array.

Returns Value

The array_pop() function, which is used to remove the last element from an array, returns the removed element. It also returns NULL, if the array is empty, or is not an array.

For example: Using string elements

snippet
<?php
	$car = array("Mercedes", "Creta", "Audi", "Chevrolet", "Skoda");
	echo "Arraylist: ";
	print_r($car);
	$remove = array_pop($car);
	echo "</br>Removed element from array is: ";
	print_r($remove);
	echo "</br> Updated arraylist: ";
	print_r($car);
?>

Output

An element "Skoda" is removed from the end of the given array, and the updated list is displayed in the given output.

Output
Arraylist: Array ( [0] => Mercedes [1] => Creta [2] => Audi [3] => Chevrolet [4] => Skoda ) Removed element from array is: Swift Updated arraylist: Array ( [0] => Mercedes [1] => Creta [2] => Audi [3] => Chevrolet )

Example: Using numeric keys

snippet
<?php
	$mall = array(1 => "DLF", 2 => "GIP", 3 => "V3S");
	echo "Removed element: ".array_pop($a). "</br>";
	print_r($mall);
?>

Output

Output
Removed element: Jupiter Array ( [1] => DLF [2] => GIP )

Example: Using numeric values

snippet
<?php
	$numbers = array(45, 76, 23, 91, 82, 39);
	$removed = array_pop($numbers);
	echo "Removed array element is: ". $removed; 
	echo "</br> Update array is: ";
	print_r($numbers);
?>

Output

An element 39 is removed from the end of the given array, as you can see in the below output.

Output
Removed array element is: 39 Update array is: Array ( [0] => 45 [1] => 76 [2] => 23 [3] => 91 [4] => 82 )
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents