downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_product> <array_pad
[edit] Last updated: Fri, 25 May 2012

view this page in

array_pop

(PHP 4, PHP 5)

array_popExtrae el último elemento del final del array

Descripción

mixed array_pop ( array &$array )

array_pop() extrae y devuelve el último valor del array, acortando el array con un elemento menos. Si el array está vacío (o no es un array), se devolverá NULL. Además se producirá un Warning cuando se llame a un elemento que no es un array.

Nota: Esta función ejecutará un reset() en el puntero de array del array de entrada después de su uso.

Parámetros

array

El array de donde obtener el valor.

Valores devueltos

Devuelve el último valor del array. Si el array está vacío (o no es un array), se devolverá NULL.

Ejemplos

Ejemplo #1 Ejemplo de array_pop()

<?php
$stack 
= array("naranja""plátano""manzana""frambuesa");
$fruit array_pop($stack);
print_r($stack);
?>

Después de hacer esto, $stack solo tendrá 3 elementos:

Array
(
    [0] => naranja
    [1] => plátano
    [2] => manzana
)

y raspberry será asignado a $fruit.

Ver también



array_product> <array_pad
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes array_pop
sven dot uselesspart at e7o dot de 31-Mar-2012 09:40
If you get an error like "Warning: Cannot add element to the array as the next element is already occupied" you shouldn't use the array_pop-function. You can use the unset-function instead:

echo $a[count($a)-1]; // or end($a)
unset($a[count($a)-1]);

The reason is that array_pop doesn't update the internal structures of the array in the way you're expecting, only unset will work in some special cases with extended using the stack.
qeremy 07-Mar-2012 11:26
For the sake of array_unshift()
:)

<?php
function array_unpop(&$arr) {
   
$args = func_get_args(); unset($args[0]);
   
$tarr = array();
    foreach (
$args as $arg) {
       
$tarr[] = $arg;
    }
   
$arr = array_merge($arr, $tarr);
}

$queue = array("orange", "banana");
array_unpop($queue, "apple", "raspberry");
print_r($queue);
?>

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
mtroy dot student at gmail dot com 16-Dec-2010 06:39
to apply arra_pop serveral times but not recursive

<?php
function array_mpop($array, $iterate)
{
    if(!
is_array($array) && is_int($iterate))
        return
false;

    while((
$iterate--)!=false)
       
array_pop($array);
    return
$array;
}
?>

for test :

<?php
    $a
= array("titi", "toto", "tata", "tonton", "toutou", "tutu");
   
$a = array_mpop($a, 2);
   
var_dump($a);
?>

result :

array(4) { [0]=> string(4) "titi" [1]=> string(4) "toto" [2]=> string(4) "tata" [3]=> string(6) "tonton" }
bellefy at yahoo dot com 27-Aug-2010 09:35
Regarding the last few comments.

To delete the first item in an array:
<?php
array_shift
($array);
?>

To get the filename or the file's mtime:
<?php
$filename
= basename(__FILE__);
$mod = filemtime(__FILE__);
?>
benjamin_letchford at student dot rmit dot edu dot au 27-Aug-2010 02:24
Want to delete the first element in an array? Here's a small and handy function that'll do the trick!

function array_pop_first(&$array) {
    $array = array_reverse($array);
    array_pop($array);
    $array = array_reverse($array);
}
macnimble at gmail dot com 18-Jul-2010 01:37
@Jochen

You could use PHP's pathinfo function to achieve the same results:

<?php
$mod
= filemtime(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
?>
me at fxless dot org 18-Feb-2010 01:38
I have used array_pop() in a function that returns the name of the current file. This can be used, for example, in conjunction with filemtime() to get the modification time of the current file. The function I coded is a one-liner:

<?php
   
function whoAmI(){
        return
array_pop(explode("/", $_SERVER['PHP_SELF']));
    }
?>

If your file URI is www.example.com/bar/foobar.php, whoAmI() will return foobar.php. To use it with e.g. filemtime() you would simply write:

<?php
    $modtime
= filemtime(whoAmI());
?>

Greetings,
Jochen
jim203nospamplz at plznospamaol dot com 05-Sep-2009 04:51
2 line changes to my previous submission:

$theJumpNumber = (round(count($temparray)/2) + $startingFileNumber) % count($temparray); // use of startingfilenumber randomizes the jump number
while (count($temparray) % $theJumpNumber == 0
|| !isPrime($theJumpNumber)) // !isPrime as easy way to check for no cofactors

You need to check for no cofactors so you can cycle round the complete array without duplicates. Checking !isPrime on theJumpNumber is a pretty easy way to do that. isPrime can be found by google: php isprime
sneskid at hotmail dot com 03-Aug-2009 07:22
As already mentioned, array_pop always returns a copy, never a reference, which can be a problem in some cases.

Here is a pop function that allows you to get the reference.
(keep in mind it will alter the internal pointer of the array)
<?php
function &array_rpop(&$a){
   
end($a);
   
$k=key($a);
   
$v=&$a[$k];
    unset(
$a[$k]);
    return
$v;
}

// try this:
$A='A';
$B=array(&$A);

//$C=&array_rpop($B); // will work
$C=&array_pop($B); // won't work

$C='C';

var_dump($A,$B,$C);
?>

I hope the PHP people will make the regular function work with references.
Igor Feghali 04-Feb-2009 09:18
Beware that array_pop() returns a copy of the element (even if the array element is a reference). That means you will get different results on PHP 4 and 5 when dealing with objects.

<?php
$a
= new stdClass();
$a->foo = 'bar';

$arr = array(&$a);
$b = array_pop($arr);

$b->foo = 'baz';

var_dump($a);
?>

Output of PHP 5.2.8:
object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "baz"
}

Output of PHP 4.4.9:
object(stdClass)(1) {
  ["foo"]=>
  string(3) "bar"
}

For more information please refer to:
http://br2.php.net/manual/en/language.oop5.references.php
mcgroovin at gmail dot com 23-Oct-2008 12:13
I wrote a simple function to perform an intersect on multiple (unlimited) arrays.

Pass an array containing all the arrays you want to compare, along with what key to match by.

<?php
function multipleArrayIntersect($arrayOfArrays, $matchKey)
{
   
$compareArray = array_pop($arrayOfArrays);
   
    foreach(
$compareArray AS $key => $valueArray){
        foreach(
$arrayOfArrays AS $subArray => $contents){
            if (!
in_array($compareArray[$key][$matchKey], $contents)){
                unset(
$compareArray[$key]);
            }
        }
    }

    return
$compareArray;
}
?>
tom at sirwhite dot com 26-May-2008 10:37
@Orsi
correct me if I'm wrong... but an easier version might be
<?php
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array:    the array (in/out)
*             $deleteIt: the value which we would like to delete
*             $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
*                          if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
   
$key = array_search($deleteIt,$array,TRUE);
    if(
$key === FALSE)
        return
FALSE;
    unset(
$array[$key]);
    if(!
$useOldKeys)
       
$array = array_values($array);
    return
TRUE;
}
?>

--untested but should work.. rite?--
sonetti at hotmail dot com 05-Feb-2008 01:15
@smp_info
I think you are still tired. What would be wrong with:

<?php
$array
= array('one', 'two', 'three', 'four');

//pop the last element off
array_pop($array);

//$array == array('one', 'two', 'three');
?>

As the documentation clearly notes, array_pop() not only returns the last element, but actually removes it from the array wich is passed by reference. Calling array_diff is a waste of resources.
Orsi 10-Jan-2008 07:05
Hi,

Here is a simple function which delete one element from the array (with value):
<?php
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array:    the array (in/out)
*             $deleteIt: the value which we would like to delete
*             $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
*                          if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
   
$tmpArray = array();
   
$found = FALSE;
    foreach(
$array as $key => $value)
    {
        if(
$value !== $deleteIt)
        {
            if(
FALSE === $useOldKeys)
            {
               
$tmpArray[] = $value;
            }
            else
            {
               
$tmpArray[$key] = $value;
            }
        }
        else
        {
           
$found = TRUE;
        }
    }
  
   
$array = $tmpArray;
  
    return
$found;
}
?>

Maybe it will help somebody...
smp_info at yahoo dot com 26-Nov-2007 03:44
I'm sorry, I must have been extremely tired when writing the note below.  :P

Replace $element with $array, and the code will work nicely.

The right code would be..

<?php
//$array = array('one', 'two', 'three', 'four');

//pop the last element off and return the array
$array = array_diff($array, array(array_pop($array)));

//$array = array('one', 'two', 'three');
smp_info at yahoo dot com 19-Nov-2007 04:23
I've found myself several times wanting the array (minus the popped element) returned, instead of the element returned.

The following code does this nicely:

<?php
//$array = array('one', 'two', 'three', 'four');

//pop the last element off and return the array
$array = array_diff($array, array(array_pop($element)));

//$array = array('one', 'two', 'three');
doyley3731 at gmail dot com 31-Oct-2007 04:37
I had a problem when using this function because my array was made up entirley of numbers, so I have made my own function.  Hopefully it will be useful to somebody.

function array_trim_end($array){

$num=count($array);
$num=$num-1;
unset($array[$num]);

return $array;
}
rmondragon at gmail dot com 07-Jun-2005 02:03
In a previous example ...
<?php
function array_trim ( $array, $index ) {
   if (
is_array ( $array ) ) {
     unset (
$array[$index] );
    
array_unshift ( $array, array_shift ( $array ) );
     return
$array;
     }
   else {
     return
false;
     }
   }
?>

This have a problem. if u unset the last value and then use
<?
array_unshift ( $array, array_shift ( $array ) );
?>

will return a :  Array ( [0] => )
so u can fix it using...

<?php
if (count($array) > 0) array_unshift ( $values, array_shift ( $values ) );           
?>

good luck ;)
15-Dec-2004 08:29
strrchr is a lot more useful than the other example using array_pop for finding the extension of a file. For example:

<?php
$ext
= strrchr($filename, ".");
?>

$ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "filename.tar.gz", then this construction will just return the last extension.
eddie at metafoundry dot com 25-Nov-2004 08:35
Quick way to get the extension from a file name using array_pop:

$ext = array_pop(explode(".",$filename));
30-Mar-2004 01:55
A function to delete an array value that recalculates the index ( its very short and easy to understand ).
Hope this might help someone...

<?php
/* Usage:
    $array : Array
    $indey : Integer
   
    The value of $array at the index $index will be
    deleted by the function.
*/
function array_trim ( $array, $index ) {
   if (
is_array ( $array ) ) {
      unset (
$array[$index] );
     
array_unshift ( $array, array_shift ( $array ) );
      return
$array;
      }
   else {
      return
false;
      }
   }
?>
Alex Dowgailenko 15-Dec-2003 03:36
array_pop() can be usefull for fetching extentions of files, especially in cases where there might be more than one period in the filename.

eg:

<?php
$filename
= "textfile.txt.bak";
$tmp = explode(".", $filename);
$ext = array_pop($tmp);

print_r($ext); // Shows "bak"
?>
21-Oct-2003 01:46
Be aware that using array_pop on an associative array that uses a numeric string as a key changes the key:

<?php
$stack
= array("12" => "green", "54" => "brown", "672" => "blue");
print_r($stack);
$fruit = array_pop($stack);
print_r($stack);
?>

Results of execution:
Array
(
    [12] => green
    [54] => brown
    [672] => blue
)
Array
(
    [0] => green
    [1] => brown
)

However, if there is a non-numeric character in the key, the key will be maintained:

<?php
$stack
= array("g1" => "green", "b1" => "brown", "b2" => "blue");
print_r($stack);
$fruit = array_pop($stack);
print_r($stack);
?>

Results of execution:
Array
(
    [g1] => green
    [b1] => brown
    [b2] => blue
)
Array
(
    [g1] => green
    [b1] => brown
)
ryan8613(at)hotmail(dot)com 08-Jun-2003 06:10
A function that may help some out, considering it's pretty much the one mentioned previously...

<?php
function array_trim($arr, $indice) {
        if(!isset(
$indice)) {
               
$indice = count($arr)-1;
        }
        unset(
$arr[$indice]);
       
array_shift($arr);
        return
$arr;
}
?>

It cuts the given index value off of the array, but without the shift, if  the 'index' value isn't given, it cuts off the end value.
Alex Chacón 28-Feb-2003 05:16
alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes

<?php
function eliminarElementoArreglo ($array, $indice)
{
    if (
array_key_exists($indice, $array))
    {
       
$temp = $array[0];
       
$array[0] = $array[$indice];
       
$array[$indice] = $temp;
       
array_shift($array);

       
//reacomodamos índices
       
for ($i = 0 ; $i < $indice ; $i++)
        {
           
$dummy = $array[$i];
           
$array[$i] = $temp;
           
$temp = $dummy;
        }
    }
    return
$array;
}
?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites