PHP array_pop() Function

PHP array_pop() function is “used to remove the last element of an array.” It reduces the size of an array by one since the last item is removed from the array.

Syntax

array_pop($array)

Parameters

array(required): It is the array whose element will be removed.

Return value

It returns the last element of the array. null is returned if the array is empty.

Visual RepresentationVisual Representation of PHP array_pop() Function

Example 1: How to Use array_pop() Function

<?php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];

echo "Before pop : \n";

print_r($netflix);

$removedElement = array_pop($netflix);

echo "Removed element : ";

echo $removedElement."\n";

echo "After pop : \n";

print_r($netflix);

Output

Before pop : 
Array
(
 [0] => Stranger Things
 [1] => Black Mirror
 [2] => Bright
 [3] => XOXO
)
Removed element : XOXO
After pop : 
Array
(
 [0] => Stranger Things
 [1] => Black Mirror
 [2] => Bright
)

Example 2: Passing an empty arrayVisual Representation of Passing an empty array

<?php

$netflix = [];
$removedElement = array_pop($netflix);

echo $removedElement;

Output

 

You can see it didn’t output anything which means it returns null and it represents the absence of a value.

Example 3: Using Associative Array

<?php

$arr = ['name' => 'Krunal', 'education' => 'BE', 'business' => 'IT' ];

echo "Before pop : \n";

print_r($arr);

echo "Removed element : ";

echo array_pop($arr)."\n";

echo "After pop : \n";

print_r($arr);

Output

Before pop : 
Array
(
 [name] => Krunal
 [education] => BE
 [business] => IT
)
Removed element: IT
After pop : 
Array
(
 [name] => Krunal
 [education] => BE
) 

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.