array_shift

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

array_shiftDespila un elemento al principio de un array

Descripción

function array_shift(array &$array): mixed

array_shift() extrae el primer valor del array array y lo devuelve, acortando array en un elemento, y desplazando todos los elementos hacia abajo. Todas las claves numéricas serán modificadas para comenzar en cero mientras que las claves literales no serán afectadas.

Nota:

Esta función ejecutará reset() sobre el puntero del array de entrada después de usarlo.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve el valor despilado, o null si el array está vacío o si el valor de entrada no es un array.

Ejemplos

Ejemplo #1 Ejemplo con array_shift()

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

El ejemplo anterior mostrará:

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

y orange ha sido colocado en $fruit.

Véase también

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 = array(
  2 => '(2)',
  1 => '(1)',
  0 => '(0)',
);                         print_r( $shifty );

array_shift( $shifty );    print_r( $shifty );
//     [0] => (1)
//     [1] => (0)

array_pop( $poppy );       print_r( $poppy );
//     [2] => (2)
//     [1] => (1)

$shifty = $poppy = array(
  'a' => 'A',
  'b' => 'B',
  '(0)',
  '(1)',
  'c' => 'C',
  'd' => 'D',
);                                     print_r( $shifty );

array_shift( $shifty );                print_r( $shifty );
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C
//     [d] => D

array_unshift( $shifty, 'unshifted');  print_r( $shifty );
//     [0] => unshifted
//     [b] => B
//     [1] => (0)
//     [2] => (1)
//     [c] => C
//     [d] => D

array_pop( $poppy );                   print_r( $poppy );
//     [a] => A
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C

array_push( $poppy, 'pushed');         print_r( $poppy );
//     [a] => A
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C
//     [2] => pushed

?>
up
5
chris {at} w3style {dot} co {dot} uk
17 years ago
As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn't return the first element by reference.  This may seem like very unexpected behaviour.  If you're working with a collection of references (in my case XML Nodes) this should do the trick.

<?php

/**
 * This function exhibits the same behaviour is array_shift(), except
 * it returns a reference to the first element of the array instead of a copy.
 *
 * @param array &$array
 * @return mixed
 */
function &array_shift_reference(&$array)
{
  if (count($array) > 0)
  {
    $key = key($array);
    $first =& $array[$key];
  }
  else
  {
    $first = null;
  }
  array_shift($array);
  return $first;
}

class ArrayShiftReferenceTest extends UnitTestCase
{
    
  function testFunctionRemovesFirstElementOfNumericallyIndexedArray()
  {
    $input = array('foo', 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionRemovesFirstElementOfAssociativeArray()
  {
    $input = array('x' => 'foo', 'y' => 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('y' => 'bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionReturnsReferenceToFirstElementOfNumericallyIndexedArray()
  {
    $foo = 'foo';
    $input = array(&$foo, 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsReferenceToFirstElementOfAssociativeArray()
  {
    $foo = 'foo';
    $input = array('x' => &$foo, 'y' => 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsNullIfEmptyArrayPassedAsInput()
  {
    $input = array();
    $first = array_shift_reference($input);
    $this->assertNull($first, '%s: Array has no first element so NULL should be returned');
  }

}

?>
up
4
michaeljanikk at gmail dot com
12 years ago
To remove an element from the MIDDLE of an array (similar to array_shift, only instead of removing the first element, we want to remove an element in the middle, and shift all keys that follow down one position)

Note that this only works on enumerated arrays.

<?php
$array = array('a', 'b', 'c', 'd', 'e', 'e');
/*
array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "e"
}
*/

$indexToRemove = 2;
unset($array[$indexToRemove]);
$array = array_slice($array, 0);

/*
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "d"
  [3]=>
  string(1) "e"
  [4]=>
  string(1) "e"
}
*/
?>

I hope this helps someone!
up
2
mah dot di at live dot com
10 years ago
This removeAdd function, the first argument shift your array then unshif the second argument to your array. first argument is an array and second argument can be int or str.

<?php
function removeAdd ($arr, $newer){
    $a = array_shift($arr);
    $b = array_unshift($arr, $newer);
    foreach ($arr as $value){
        echo $value."<br />";
    }
}

$a = array(1,2,3,4,5,6);
foreach ($a as $current){
    echo $current."<br />";
}
echo "<hr />";
removeAdd($a, 0);
?>

OUTPUT:
1
2
3
4
5
6
_______

0
2
3
4
5
6
up
5
Traps
19 years ago
For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

<?php

// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 1, b = 2

// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 2, b = 2

?>
up
5
arturo {dot} ronchi {at} gmail {dot} com
21 years ago
Here is a little function if you would like to get the top element and rotate the array afterwards.

function array_rotate(&$arr)
{
  $elm = array_shift($arr);
  array_push($arr, $elm);
  return $elm;
}
up
2
Anonymous
21 years ago
This function will save the key values of an array, and it will work in lower versions of PHP:

<?php

function array_shift2(&$array){
    reset($array);
    $key = key($array);
    $removed = $array[$key];
    unset($array[$key]);
    return $removed;
}

?>
up
1
Anonymous
20 years ago
<?php

//----------------------------------------------------------
// The combination of array_shift/array_unshift 
// greatly simplified a function I created for 
// generating relative paths. Before I found them 
// the algorithm was really squirrely, with multiple 
// if tests, length calculations, nested loops, etc. 
// Great functions.
//----------------------------------------------------------

function create_relative_path($inSourcePath, $inRefPath)
{
    // break strings at slashes
    $s_parts            = explode('/', $inSourcePath);
    $r_parts            = explode('/', $inRefPath);
    
    // delete items up to the first non-equal part
    while ($s_parts[0] === $r_parts[0])
    {
        array_shift($s_parts);
        array_shift($r_parts);
    }
    
    // add wild card to r_parts for each remaining 
    // item of s_parts
    while ($s_parts[0])
    {
        array_unshift($r_parts, '..');
        array_shift($s_parts);
    }
    
    return implode('/', $r_parts);
}

//----------------------------------------------------------
// Example:
//     Given a source path $sp generates the relative 
//     location of $rp. $sp could be assigned using 
//     $_SERVER['PHP_SELF'] but it's hardcoded for 
//     the example.
//----------------------------------------------------------
$sp