array_shift

(PHP 4, PHP 5, PHP 7, PHP 8)

array_shiftВитягує елемент з початку масиву

Опис

function array_shift(array &$array): mixed

array_shift() витягує з початку масиву array елемент та повертає його значення, скорочуючи масив на один елемент. Всі числові ключі масиву будуть перетворені, щоб починати відлік з нуля, тоді як рядкові ключі не зміняться.

Зауваження:

Ця функція скидатиме() вказівник array вхідного масиву після використання.

Параметри

array

Вхідний масив.

Значення, що повертаються

Повертає витягнуте значення або null, якщо array є порожнім або не є масивом.

Приклади

Приклад #1 Приклад використання array_shift()

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

Поданий вище приклад виведе:

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

а значення orange буде встановлено в змінну $fruit.

Прогляньте також

  • array_unshift() - Prepend one or more elements to the beginning of an array
  • array_push() - Push one or more elements onto the end of array
  • array_pop() - Pop the element off the end of array

add a note

User Contributed Notes 29 notes

up
119
regs at voidship dot net
17 years ago
Using array_shift over larger array was fairly slow.  It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn't need to reindex the array and will preserve keys if you want it to (didn't matter in my case).  

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop.  It also requires sequential numeric keys.
up
64
elad dot yosifon at gmail dot com
13 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.
up
23
nospam at dyce dot losethisbit dot com
18 years ago
Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me ;-)

<?php

function array_kshift(&$arr)
{
  list($k) = array_keys($arr);
  $r  = array($k=>$arr[$k]);
  unset($arr[$k]);
  return $r;
}

// test it on a simple associative array
$arr = array('x'=>'ball','y'=>'hat','z'=>'apple');

print_r($arr);
print_r(array_kshift($arr));
print_r($arr);

?>

Output:

Array
(
    [x] => ball
    [y] => hat
    [z] => apple
)
Array
(
    [x] => ball
)
Array
(
    [y] => hat
    [z] => apple
)
up
8
biziclop at vipmail dot hu
8 years ago
<?php

//Be careful when using array_pop/shift/push/unshift with irregularly indexed arrays:

$shifty = $poppy