AppDividend
Latest Code Tutorials

PHP Array Pop Example | PHP array_pop() Function Tutorial

0

PHP Array Pop Example | PHP array_pop() Function Tutorial is today’s topic. PHP pop() function removes the last element of an array. The array_pop() function deletes the last element of an array. If you do not know how to add the values into an array, then check out array_push() function tutorialIf an array is empty (or is not an array), NULL will be returned. An array_pop() function will produce an error of level E_WARNING when called on a non-array.

PHP Array Pop Example

The array_pop function Pops the element off the end of an array. See the following syntax of array_pop() function.

array_pop(array)

An array argument is required which is the array whose elements will be removed.

See the following example.

<?php

// app.php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];
$removedElement = array_pop($netflix);

print_r($netflix);
echo $removedElement."\n";

The output of the code is following.

 

PHP array_pop() Function Tutorial

So, array_pop() function always returns the removedElement.

 It reduces the size of an array by one since the last item is removed from an array.

Let’s see the example where an array is empty.

<?php

// app.php

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

print_r($netflix);
echo $removedElement;

The output is following.

 

PHP Array Pop Example

PHP Array unset() Function

If we want to remove an individual element from an array, then we can use the unset() function.

It does not return anything; it just removes the element from the specified index from an array. See the following example.

<?php

// app.php

$netflix = ['Krunal', 'Ankit', 'Rushabh'];
unset($netflix[2]);

print_r($netflix);

The output is following.

 

PHP Array unset() Function

So, it has removed the 2nd indexed element which is Rushabh.

So, if we want to remove the last element, we can use the array_pop() function, and if we want to remove an element at the specified position, then we can use the PHP array unset() function.

Notice that the unset() function leaves a gap in our numerically indexed array. That means if we have an array of length 6 and if we are removing an index of 4, then remaining array has the index of 0, 1, 2, 3, 5, 6. 4th index will be removed from an array.

Finally, PHP Array Pop Example | PHP array_pop() Function Tutorial is over.

Leave A Reply

Your email address will not be published.

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