Share on Google+Share on Google+

PHP Array Pop

Advertisement
PHP Array Pop - This tutorial covers up an essential function of PHP called array_pop(), array_pop() function is used to pop the last value of an array. Several examples of array_pop() illustrates the use of pop function of PHP.

PHP Array Pop() function

In PHP array_pop() function pop the last element of an array.

General Format

mixed array_pop(array $array)

Parameters 

array $array: Input array

Return Value

Returns the last value of the array

The PHP array_pop() function works same as the pop() function does in a Stack, after poping the first input, it reset  the array pointer. If an array is empty it will return NULL.

Example 1:

<?php

$stack=array("cricket","rugby","soccer","basketball");

echo"<b>Original array before pop function</b><br/>";

print_r($stack);

$game=array_pop($stack);

echo"<br/><b>After using pop() function elements of array is now:</b><br/>";

print_r($stack);

echo"<br/><B>Value of \$game is:</b><br/>";

echo$game;

?>

Output:

Original array before pop function
Array ( [0] => cricket [1] => rugby [2] => soccer [3] => basketball )
After using pop() function elements of array is now:
Array ( [0] => cricket [1] => rugby [2] => soccer )
Value of $game is:
basketball

Example 2:

<?php

$array=array();

echo array_pop($array);

?>

Output:

 

(Blank page. will be displayed as output)

Example 3:

<?php

$array=array(0,1,2,3,4);

echo"<b> Elements of the array are:</b><br/>";

print_r($array);

array_pop($array);

echo"<br/><b> Elements of the array after being poped are:</b><br/>";

print_r($array);

echo"<br/><b> Elements of the array after elements being pushed are:</b><br/>";

array_push($array,55,777);

print_r($array);

echo"<br/><b> Elements of the array after again being poped are:</b><br/>";

array_pop($array);

print_r($array);

?>

Output:

Elements of the array are:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )
Elements of the array after being poped are:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
Elements of the array after elements being pushed are:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 55 [5] => 777 )
Elements of the array after again being poped are:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 55 )

Advertisements

Advertisement

Posted on: October 23, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.