array_pop
array_pop() извлекает и возвращает значение последнего элемента массива array , уменьшая размер array на один элемент.
Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.
Список параметров
Массив, из которого берётся значение.
Возвращаемые значения
Возвращает значение последнего элемента массива array . Если array пуст, будет возвращён null .
Примеры
Пример #1 Пример использования array_pop()
$stack = array( «orange» , «banana» , «apple» , «raspberry» );
$fruit = array_pop ( $stack );
print_r ( $stack );
?>?php
После этого в $stack будет только 3 элемента:
Array ( [0] => orange [1] => banana [2] => apple )
и raspberry будет присвоено переменной $fruit .
Смотрите также
- array_push() — Добавляет один или несколько элементов в конец массива
- array_shift() — Извлекает первый элемент массива
- array_unshift() — Добавляет один или несколько элементов в начало массива
User Contributed Notes 11 notes
10 years ago
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.
2 years ago
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.
15 years ago
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.
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 ]);
>
>
>
18 years ago
In a previous example .
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.
if ( count ( $array ) > 0 ) array_unshift ( $values , array_shift ( $values ) );
?>
good luck 😉
20 years ago
alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes
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 ;
>
?>
16 years ago
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.
Как получить последний элемент php массива
Смотря что подразумевается под словом «получить». Если нужно именно извлечь (получить элемент и уменьшить длину массива) последний элемент массива, то можно воспользоваться функцией array_pop() :
$numbers = [1, 2, 3, 4]; $lastNumber = array_pop($numbers); print_r($numbers); //=> [1, 2, 3] // Исходный массив уменьшился на один элемент
А если изменять исходный массив нельзя, то можно воспользоваться функцией array_key_last() . Эта функция получает ключ последнего элемента массива, а потом можно получить и сам последний элемент. Взгляните на пример:
$numbers = [1, 2, 3, 4]; $lastNumber = $numbers[array_key_last($numbers)]; print_r($numbers); //=> [1, 2, 3, 4] // Исходный массив при этом не изменился
08 ноября 2022
Поиск последнего элемента PHP массива с помощью функции count() .
Подсчитывает количество элементов массива.
$numbers = ['one', 'two', 'three', 'four']; $count = count($numbers); // => 4 $lastKey = count($numbers) - 1; // => 3 $lastValue = $numbers[$lastKey]; echo($lastValue); // => four
Как извлечь последний элемент php массива
Существует множество способов решения данной задачи. Я расскажу о парочке из них.
Если массив не нужно никак модифицировать, то можно использовать функцию array_key_last() , которая возвращает индекс последнего элемента. Лучше сразу взглянуть на пример:
$words = ['hexlet', 'potato', 'green']; $lastItem = $words[array_key_last($words)]; print_r($lastItem); // => 'green'
Также можно использовать встроенную функцию array_pop() . Она извлекает последний элемент и возвращает его значение, но нужно помнить о том, что при этом исходный массив уменьшается на один элемент.
$words = ['hexlet', 'potato', 'green', 'smith']; $lastItem = array_pop($words); print_r($lastItem); //=> 'smith' print_r($words); //=> ['hexlet', 'potato', 'green']
Как получить последний элемент массива php
(PHP 4, PHP 5, PHP 7, PHP 8)
end — Устанавливает внутренний указатель массива на его последний элемент
Описание
end ( array | object &$array ): mixed
end() устанавливает внутренний указатель array на последний элемент и возвращает его значение.
Список параметров
Массив. Передаётся по ссылке, потому что он модифицируется данной функцией. Это означает, что необходимо передать его как реальную переменную, а не как функцию, возвращающую массив, так как по ссылке можно передавать только фактические переменные.
Возвращаемые значения
Возвращает значение последнего элемента или false для пустого массива.
Список изменений
| Версия | Описание |
|---|---|
| 8.1.0 | Вызов функции в объекте ( object ) объявлен устаревшим. Либо сначала преобразуйте объект ( object ) в массив ( array ) с помощью функции get_mangled_object_vars() , либо используйте методы, предоставляемые классом, реализующим интерфейс Iterator , например, ArrayIterator . |
| 7.4.0 | Экземпляры классов SPL теперь обрабатываются как пустые объекты, не имеющие свойств, вместо вызова метода Iterator с тем же именем, что и эта функция. |
Примеры
Пример #1 Пример использования end()
$fruits = array( ‘apple’ , ‘banana’ , ‘cranberry’ );
echo end ( $fruits ); // cranberry
Смотрите также
- current() — Возвращает текущий элемент массива
- each() — Возвращает текущую пару ключ/значение из массива и смещает его указатель
- prev() — Передвигает внутренний указатель массива на одну позицию назад
- reset() — Устанавливает внутренний указатель массива на его первый элемент
- next() — Перемещает указатель массива вперёд на один элемент
- array_key_last() — Получает последний ключ массива
User Contributed Notes 15 notes
12 years ago
It’s interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:
$a = array();
$a [ 1 ] = 1 ;
$a [ 0 ] = 0 ;
echo end ( $a );
?>
This will print «0».
17 years ago
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:
// Returns the key at the end of the array
function endKey ( $array ) end ( $array );
return key ( $array );
>
?>
Usage example:
$a = array( «one» => «apple» , «two» => «orange» , «three» => «pear» );
echo endKey ( $a ); // will output «three»
?>
11 years ago
If all you want is the last item of the array without affecting the internal array pointer just do the following:
function endc ( $array )
$items = array( ‘one’ , ‘two’ , ‘three’ );
$lastItem = endc ( $items ); // three
$current = current ( $items ); // one
?>
This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
21 years ago
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:
9 years ago
I found that the function end() is the best for finding extensions on file name. This function cleans backslashes and takes the extension of a file.
private function extension ( $str ) $str = implode ( «» , explode ( «\\» , $str ));
$str = explode ( «.» , $str );
$str = strtolower ( end ( $str ));
return $str ;
>
// EXAMPLE:
$file = ‘name-Of_soMe.File.txt’ ;
echo extension ( $file ); // txt
?>
Very simple.
10 years ago
php v5.4 does not support the following statement.
echo end(explode(«.», $filename)); // return jpg string
instead you have to split into 2 statements
$file = explode(«.», $filename);
echo end ($file);
18 years ago
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:
echo «>> » . end ( array_keys (array( ‘x’ => ‘y’ ))). «\n» ;
?>
which will return «Fatal error: Only variables can be passed by reference» in version
If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:
$x = array_keys (array( ‘x’ => ‘y’ ));
echo «>> » . end ( $x ). «\n» ;
5 years ago
13 years ago
this is a function to move items in an array up or down in the array. it is done by breaking the array into two separate arrays and then have a loop creates the final array adding the item we want to move when the counter is equal to the new position we established the array key, position and direction were passed via a query string
//parameters
//$array- the array you are modifying
//$keytomove — the key of the item you wish to move
//$pos — the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir — the direction you want to move it — «up»/»dn»
function change_pos ( $array , $keytomove , $pos , $dir ) <
//count the original number of rows
$count = count ( $array );
//set the integer we will use to place the moved item
if( $dir == «up» ) <
if( $pos == 1 ) <
//if the item is already first and we try moving it up
//we send it to the end of the array
$change = $count ;
>else <
//anywhere else it just moves back one closer to the start of the array
$change = $pos — 1 ;
>
>
//do the same for the down button
if( $dir == «dn» ) <
if( $pos == $count ) <
$change = 1 ;
>else <
$change = $pos + 1 ;
>
>
//copy the element that you wish to move
$move = $array [ $keytomove ];
//delete the original from the main array
unset( $array [ $keytomove ]);
//create an array of the names of the values we
//are not moving
$preint = 1 ;
foreach( $array as $c ) <
$notmoved [ » < $preint >» ] = $c [ ‘name’ ];
$preint ++;
>
//loop through all the elements
$int = 1 ;
while( $int //dynamically change the key of the unmoved item as we increment the counter
$notmovedkey = $notmoved [ » $int » ];
//when the counter is equal to the position we want
//to place the moved entry we pump it into a new array
if( $int == $change ) <
$neworder [ » < $keytomove >» ] = $move ;
>
//add all the other array items if the position number is not met and
//resume adding them once the moved item is written
if( $contkey != «» ) <
$neworder [ » < $notmovedkey >» ] = $array [ » < $notmovedkey >» ];
>
$int ++;
>
return( $neworder );
>
?>
This is not too elegant but it works.
6 years ago
Attempting to get the value of a key from an empty array through end() will result in NULL instead of throwing an error or warning becuse end() on an empty array results in false:
$a = [ ‘a’ => [ ‘hello’ => ‘a1’ , ‘world’ => ‘a2’ ],
‘b’ => [ ‘hello’ => ‘b1’ , ‘world’ => ‘b2’ ],
‘c’ => [ ‘hello’ => ‘c1’ , ‘world’ => ‘c2’ ]
];
$b = [];
var_dump ( end ( $a )[ ‘hello’ ]);
var_dump ( end ( $b )[ ‘hello’ ]);
var_dump ( false [ ‘hello’ ]);
21 years ago
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won’t return the correct key value; you must first position at end() of the array:
function array_add (& $array , $value ) <
$array [] = $value ; // add an element
end ( $array ); // important!
return key ( $array );
>
?>
14 years ago
Take note that end() does not recursively set your multiple dimension arrays’ pointer to the end.
Take a look at the following:
// create the array for testing
$a = array();
$i = 0 ;
while( $i ++ < 3 )$a [] = array( dechex ( crc32 ( mt_rand ())), dechex ( crc32 ( 'lol' . mt_rand ())));
>
// show the array tree
echo » ; var_dump ( $a );
// set the pointer of $a to the end
end ( $a );
// get the current element of $a
var_dump ( current ( $a ));
// get the current element of the current element of $a
var_dump ( current ( current ( $a )));
?>
You will notice that you probably get something like this:
The array elements’ pointer are still at the first one as current. So do take note.
