array_unshift

(PHP 4, PHP 5, PHP 7)

array_unshift배열의 맨 앞에 하나 이상의 원소를 첨가

설명

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

array_unshift()는 전달된 원소들을 array의 앞에 첨가한다. 원소 목록이 모두 첨가되면, 첨가된 원소들은 같은 순서로 남아있게 된다는 것에 유의한다. 모든 숫자 배열 키들은 리터럴 키들이 건드러지지 않는 동안에는 제로부터 카운트를 시작할수 있도록 변경될것이다.

인수

array

입력 배열.

var

앞에 붙일 변수.

반환값

array안의 새로운 원소의 수를 반환한다.

예제

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() - 배열의 마지막 원소 빼내기

add a note add a note

User Contributed Notes 13 notes

up
206
sergei at gmx dot net
17 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
35
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz
22 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
35
Anonymous
12 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
9
daniel at smallboxcms dot com
9 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
2
amschroeder at gmail dot com
17 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[$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...
up
2
php at electricsurfer dot com
20 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
robert dot wills at fuzzbrain dot uklinux dot net
22 years ago
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
up
0
eliasritter168667 at gmail dot com
11 months ago
This function helps if you want to prepend a key and value pair to the beginning of an array:

function array_kunshift(array $array, string|int $key, mixed $value): array {
        return array_merge([$key => $value], $array);
    }
up
0
Richard Akindele
8 years ago
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);
up
0
sahn at hmc dot edu
23 years ago
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);
}
?>
up
-1
chris dot NoThxSpam dot given at hp dot com
21 years ago
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);
}
?>
up
-4
John Brooking
18 years ago
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 ));
?>
up
-12
lagroue
20 years ago
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));
?>
To Top