array_unshift

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

array_unshiftEmpila uno o más elementos al inicio de un array

Descripción

function array_unshift(array &$array, mixed ...$values): int

array_unshift() añade los elementos value1, ..., pasados como argumento al inicio del array array. Se debe tener en cuenta que los elementos se añaden como un todo, y que permanecen en el mismo orden. Todas las claves numéricas se modificarán para comenzar desde cero, mientras que las claves literales no se verán afectadas.

Nota:

Reinicia el puntero interno del array al primer elemento.

Parámetros

array

El array de entrada.

values

Valor a empilar.

Valores devueltos

Devuelve el nuevo número de elementos del array array.

Historial de cambios

Versión Descripción
7.3.0 Esta función puede ahora ser llamada con un solo parámetro. Anteriormente, se requerían al menos dos parámetros.

Ejemplos

Ejemplo #1 Ejemplo con array_unshift()

<?php

$queue = [
    "orange",
    "banana"
];

array_unshift($queue, "apple", "raspberry");

var_dump($queue);

?>

El ejemplo anterior mostrará:

array(4) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(9) "raspberry"
  [2]=>
  string(6) "orange"
  [3]=>
  string(6) "banana"
}

Ejemplo #2 Uso con arrays asociativos

Si un array asociativo es añadido como prefijo a otro array asociativo, el array añadido es indexado numéricamente en el array precedente.

<?php

$foods = [
    'apples' => [
        'McIntosh' => 'red',
        'Granny Smith' => 'green',
    ],
    'oranges' => [
        'Navel' => 'orange',
        'Valencia' => 'orange',
    ],
];

$vegetables = [
    'lettuce' => [
        'Iceberg' => 'green',
        'Butterhead' => 'green',
    ],
    'carrots' => [
        'Deep Purple Hybrid' => 'purple',
        'Imperator' => 'orange',
    ],
    'cucumber' => [
        'Kirby' => 'green',
        'Gherkin' => 'green',
    ],
];

array_unshift($foods, $vegetables);

var_dump($foods);

El ejemplo anterior mostrará:

array(3) {
  [0]=>
  array(3) {
    ["lettuce"]=>
    array(2) {
      ["Iceberg"]=>
      string(5) "green"
      ["Butterhead"]=>
      string(5) "green"
    }
    ["carrots"]=>
    array(2) {
      ["Deep Purple Hybrid"]=>
      string(6) "purple"
      ["Imperator"]=>
      string(6) "orange"
    }
    ["cucumber"]=>
    array(2) {
      ["Kirby"]=>
      string(5) "green"
      ["Gherkin"]=>
      string(5) "green"
    }
  }
  ["apples"]=>
  array(2) {
    ["McIntosh"]=>
    string(3) "red"
    ["Granny Smith"]=>
    string(5) "green"
  }
  ["oranges"]=>
  array(2) {
    ["Navel"]=>
    string(6) "orange"
    ["Valencia"]=>
    string(6) "orange"
  }
}

Véase también

add a note

User Contributed Notes 11 notes

up
212
sergei at gmx dot net
18 years ago
You can preserve keys and unshift an array with numerical indexes in a really simple way if you'll do the following:

<?php
$someArray=array(224=>'someword1', 228=>'someword2', 102=>'someword3', 544=>'someword3',95=>'someword4');

$someArray=array(100=>'Test Element 1 ',255=>'Test Element 2')+$someArray;
?>

now the array looks as follows:

array(
100=>'Test Element 1 ',
255=>'Test Element 2'
224=>'someword1',
228=>'someword2',
102=>'someword3',
544=>'someword3',
95=>'someword4'
);
up
36
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz
24 years ago
array_merge() will also reindex (see array_merge() manual entry), but the '+' operator won't, so...

<?php
$arrayone=array("newkey"=>"newvalue") + $arrayone;
?>

does the job.
up
36
Anonymous
14 years ago
Sahn's example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function: 

<?php 
function array_unshift_assoc(&$arr, $key, $val) 
{ 
    $arr = array_reverse($arr, true); 
    $arr[$key] = $val; 
    return = array_reverse($arr, true); 
} 
?>
up
11
daniel at smallboxcms dot com
11 years ago
Anonymous' associative version wasn't working for me, but it did with this small tweak:

function array_unshift_assoc(&$arr, $key, $val) 
{ 
    $arr = array_reverse($arr, true); 
    $arr[$key] = $val; 
    $arr = array_reverse($arr, true); 
    return $arr;
}
up
3
php at electricsurfer dot com
22 years ago
even simpler unshifting of a reference !
<?php
/**
 * @return int
 * @param $array array
 * @param $value mixed
 * @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
 */
function array_unshift_ref(&$array, &$value)
{
   $return = array_unshift($array,'');
   $array[0] =& $value;
   return $return;
}
?>
up
2
amschroeder at gmail dot com
19 years ago
This becomes a nice little problem if you index your arrays out of order (while manually sorting).  For example:

<?php
$recordMonths[3] = '8/%/2006';
$recordMonths[4] = '7/%/2004';
$recordMonths[0] = '3/%/2007';
$recordMonths[1] = '2/%/2007';
$recordMonths[5] = '12/%/2000';
$recordMonths[6] = '11/%/2000';
$recordMonths[7] = '10/%/2000';
$recordMonths[2] = '1/%/2007';

for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
array_unshift($recordMonths,'%');
for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[