array_pop

(PHP 4, PHP 5)

array_popИзвлекает последний элемент массива

Описание

mixed array_pop ( array &$array )

array_pop() извлекает и возвращает последнее значение параметра array, уменьшая размер array на один элемент. Если array пуст (или не является массивом), будет возвращён NULL. Кроме этого, если передан не массив, будет вызвано предупреждение.

Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.

Список параметров

array

Массив, из которого берется значение.

Возвращаемые значения

Возвращает последний элемент массива array. Если array пуст (или не является массивом), будет возвращен NULL.

Примеры

Пример #1 Пример использованияarray_pop()

<?php
$stack 
= array("orange""banana""apple""raspberry");
$fruit array_pop($stack);
print_r($stack);
?>

После этого, в $stack будет только 3 элемента:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

и raspberry будет присвоено переменной $fruit.

Смотрите также

  • array_push() - Добавляет один или несколько элеметов в конец массива
  • array_shift() - Извлекает первый элемент массива
  • array_unshift() - Добавляет один или несколько элементов в начало массива

Коментарии

Автор:
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 $i $indice $i++)
        {
           
$dummy $array[$i];
           
$array[$i] = $temp;
           
$temp $dummy;
        }
    }
    return 
$array;
}
?>
2003-02-28 19:16:40
http://php5.kiev.ua/manual/ru/function.array-pop.html
Автор:
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.
2004-12-15 10:29:59
http://php5.kiev.ua/manual/ru/function.array-pop.html
In a previous example ...
<?php
function array_trim $array$index ) {
   if ( 
is_array $array ) ) {
     unset ( 
$array[$index] );
     
array_unshift $arrayarray_shift $array ) );
     return 
$array;
     }
   else {
     return 
false;
     }
   }
?>

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

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

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

good luck ;)
2005-06-07 17:03:58
http://php5.kiev.ua/manual/ru/function.array-pop.html
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;
}
2007-10-31 06:37:25
http://php5.kiev.ua/manual/ru/function.array-pop.html
Автор:
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...
2008-01-10 09:05:27
http://php5.kiev.ua/manual/ru/function.array-pop.html
@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.
2008-02-05 03:15:53
http://php5.kiev.ua/manual/ru/function.array-pop.html
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;
}
?>
2008-10-23 15:13:12
http://php5.kiev.ua/manual/ru/function.array-pop.html
Автор:
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
)
2012-03-07 13:26:08
http://php5.kiev.ua/manual/ru/function.array-pop.html
Notice:
the complexity of array_pop() is O(1). 
the complexity of array_shift() is O(n).
array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.
2013-08-10 21:45:44
http://php5.kiev.ua/manual/ru/function.array-pop.html
Автор:
Strict Standards will be thrown out if you put exploded array in array_pop:
<?php
$a 
array_pop(explode(",""a,b,c"));
echo 
$a;
?>

You will see:
PHP Strict Standards:  Only variables should be passed by reference in - on line 2

Strict Standards: Only variables should be passed by reference in - on line 2
c

Notice that, you should assign a variable for function explode, then pass the variable reference into array_pop to avoid the Strict Standard warning.
2014-02-28 10:21:45
http://php5.kiev.ua/manual/ru/function.array-pop.html
Note that array_pop doesn't issue ANY warning or error if the array is already empty when you try to pop something from it. This is bizarre! And it will cause cascades of errors that are hard to resolve without knowing the real cause.

Rather than an error, it silently returns a NULL object, it appears, so in my case I ended up with warnings elsewhere about accessing elements of arrays with invalid indexes, as I was expecting to have popped an array. This behaviour (and the lack of any warning, when many trivial things are complained about verbosely) is NOT noted in the manual above. Popping an already empty stack should definitely trigger some sort of notice, to help debugging.

Sure, it's probably good practice to wrap the pop in an if (count($array)) but that should be suggested in the manual, if there's no error returned for trying something that should fail and obviously isn't expected to return a meaningful result.
2021-05-09 14:18:52
http://php5.kiev.ua/manual/ru/function.array-pop.html

    Поддержать сайт на родительском проекте КГБ