PHP 8.4.1 Released!

array_unshift

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

array_unshift一つ以上の要素を配列の最初に加える

説明

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

array_unshift() は、array の先頭に指定された要素を加えます。リストの要素は全体として加えられるため、 加えられた要素の順番は変わらないことに注意してください。 配列の数値添字はすべて新たにゼロから振りなおされます。 リテラルのキーについては変更されません。

注意:

この関数をコールすると、配列の内部ポインタは最初の要素にリセットされます。

パラメータ

array

入力の配列。

values

加える値。

戻り値

処理後の array の要素の数を返します。

変更履歴

バージョン 説明
7.3.0 この関数は、1 つのパラメータでのみ呼び出すことができるようになりました。 前は、少なくとも 2 つのパラメータが必要でした。

例1 array_unshift() の例

<?php
$queue
= [
"orange",
"banana"
];

array_unshift($queue, "apple", "raspberry");
var_dump($queue);
?>

上の例の出力は以下となります。

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

例2 連想配列と一緒に使う例

連想配列を別の連想配列の前に加える場合、 追加される配列は、もともとある配列の整数のインデックスに追加されます。

<?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);

上の例の出力は以下となります。

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"
  }
}

参考

  • array_merge() - ひとつまたは複数の配列をマージする
  • array_shift() - 配列の先頭から要素を一つ取り出す
  • array_push() - 一つ以上の要素を配列の最後に追加する
  • array_pop() - 配列の末尾から要素を取り除く

add a note

User Contributed Notes 12 notes

up
211
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
37
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
13 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
10
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
1 year 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
-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
-2
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
-5
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 ));
?>
To Top