array_unshift

(PHP 4, PHP 5, PHP 7)

array_unshift 在数组开头插入一个或多个单元

说明

array_unshift ( array &$array [, mixed $... ] ) : int

array_unshift() 将传入的单元插入到 array 数组的开头。注意单元是作为整体被插入的,因此传入单元将保持同样的顺序。所有的数值键名将修改为从零开始重新计数,所有的文字键名保持不变。

参数

array

输入的数组。

...

插入的变量。

返回值

返回 array 数组新的单元数目。

更新日志

版本 说明
7.3.0 现在可以只用一个参数来调用,之前至少需要两个参数。

范例

Example #1 array_unshift() 例子

<?php
$queue 
= array("orange""banana");
array_unshift($queue"apple""raspberry");
print_r($queue);
?>

以上例程会输出:

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

参见

  • array_shift() - 将数组开头的单元移出数组
  • array_push() - 将一个或多个单元压入数组的末尾(入栈)
  • array_pop() - 弹出数组最后一个单元(出栈)

User Contributed Notes

Richard Akindele 16-Mar-2016 06:31
Another way to tack something to the beginning of an array is with array_merge().

$plans = array('AARP'=>'Senior', 'AAA'=>'Automobile Club');

$plans = array_merge(array("BAR"=>"Best Available Rate"),  $plans);
daniel at smallboxcms dot com 17-Apr-2015 08:18
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;
}
Anonymous 19-Nov-2011 09:44
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);
}
?>
sergei at gmx dot net 03-Oct-2007 08:49
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'
);
amschroeder at gmail dot com 26-Mar-2007 09:13
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[$i];
    echo
"singleMonth: $singleMonth <br />";
}
?>

Produces:

singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007

It reindexes them based on the order they were created.  It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index.  Just my opinion...
John Brooking 02-Jun-2006 06:54
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the "side effect" of renumbering:

<?php
   array_unshift
( $myArray, array_shift( $myArray ));
?>
php at electricsurfer dot com 26-Feb-2004 06:20
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;
}
?>
lagroue 09-Nov-2003 04:46
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :

<?php
function array_unshift1 (& $ioArray, $iValueWrappedInAnArray) {
   
$lNewArray = false;
    foreach (
array_keys ($ioArray) as $lKey)
       
$lNewArray[$lKey+1] = & $ioArray[$lKey];
   
$ioArray = array (& $iValueWrappedInAnArray[0]);
    if (
$lNewArray)
        foreach (
array_keys ($lNewArray) as $lKey)
            
$ioArray[] = & $lNewArray[$lKey];
    return
count($ioArray);
}

// before last PHP (now generates a deprecation warning)
array_unshift ($a, &$v);
// since last PHP (caution, there is a wrapping array !!)
array_unshift1 ($a, array (&$v));
?>
chris dot NoThxSpam dot given at hp dot com 23-Jul-2003 12:17
If you need to change the name of a key without changing its position in the array this function may be useful.

<?php
function array_key_change($Old, $New, $In, $NewVal=NULL) {
       
$Temp = array();
        while(isset(
$Temp[$Old]) == false) {
                list(
$k, $v) = each($In);
               
$Temp[$k] = $v;
                unset(
$In[$k]);
        }
        if(
$NewVal == NULL) {
               
$NewVal = $Temp[$Old];
        }
        unset(
$Temp[$Old]);
       
$Temp = array_reverse($Temp);
       
$In = array_merge(array($New=>$NewVal), $In);
        while(list(
$k,$v) = each($Temp)) {
               
$In = array_merge(array($k=>$v), $In);
        }
        return(
$In);
}
?>
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz 30-Jul-2002 07:00
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.
robert dot wills at fuzzbrain dot uklinux dot net 07-Feb-2002 06:02
Actually this problem with the keys getting reindexed only happens when the keys are numerical:

<?php

$a
= array("f"=>"five", "s" =>"six", "t" =>
       
"twenty");

print_r($a);
echo
"\n";
foreach(
$a as $key=>$val)
{
    echo
"k: $key v: $val \n";
}

array_unshift($a, "zero");
print_r($a);
echo
"\n";
foreach(
$a as $key=>$val)
{
    echo
"k: $key v: $val \n";
}
?>

Array
(
    [f] => five
    [s] => six
    [t] => twenty
)

k: f v: five
k: s v: six
k: t v: twenty
Array
(
    [0] => zero
    [f] => five
    [s] => six
    [t] => twenty
)

k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
sahn at hmc dot edu 27-Jul-2001 12:21
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;
   
$arr = array_reverse($arr, true);
    return
count($arr);
}
?>