downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_values> <array_unique
Last updated: Fri, 30 Oct 2009

view this page in

array_unshift

(PHP 4, PHP 5)

array_unshift Fügt ein oder mehr Elemente am Anfang eines Arrays ein

Beschreibung

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

array_unshift() fügt die übergebenen Elemente am Anfang von array ein. Beachten Sie, dass die Liste von Elementen als Ganzes eingefügt wird, sodass die eingefügten Elemente die selbe Reihenfolge haben. Die numerischen Schlüssel werden so modifiziert, dass bei null zu zählen begonnen wird, Strings als Schlüssel bleiben unverändert.

Diese Funktion gibt die neue Anzahl der in array enthaltenen Elemente zurück.

Beispiel #1 array_unshift()

<?php
$queue 
= array("Orange""Banane");
array_unshift($queue"Apfel""Himbeere");
?>

Als Ergebnis enthält $queue die folgenden Elemente:

Array
(
    [0] => Apfel
    [1] => Himbeere
    [2] => Orange
    [3] => Banane
)

Siehe auch array_shift(), array_push() und array_pop().



array_values> <array_unique
Last updated: Fri, 30 Oct 2009
 
add a note add a note User Contributed Notes
array_unshift
to dot bartkus at gmail dot com -> to nicky
12-Aug-2009 10:44
Fixed solution:

Small addition to the assoc unshift below: only add if the key passed is unique

<?php
//adds a key/value pair to the beginning of an array without resetting numeric keys
function array_unshift_assoc( &$array, $key, $value, $overwrite_key = false )
{
   
//if the key can't overwrite and allready exists return false
   
if (!$overwrite_key && array_key_exists( $key, $array )) return false;
  
   
$array = array_reverse( $array, true );
   
$array[$key] = $value;
   
$array = array_reverse( $array, true );
    return
count( $array );
}
?>
nicky dot demaeyer at gmail dot com
28-Jul-2009 09:56
Small addition to the assoc unshift below: only add if the key passed is unique

<?php
//adds a key/value pair to the beginning of an array without resetting numeric keys
function array_unshift_assoc( &$array, $key, $value, $overwrite_key = false )
{
   
//if the key can't overwrite and allready exists return false
   
if (!$overwrite_key && array_key_exists( $key, $array )) return false;
   
   
array_reverse( $array, true );
   
$array[$key] = $value;
   
array_reverse( $array, true );
    return
count( $array );
}
?>
Rafael M. Salvioni
12-Jun-2008 04:52
This function inserts a element in any position of the Array, by reference.

NOTE: The array is converted for a numeric array.

<?php

/**
 * Function array_insert().
 *
 * Returns the new number of the elements in the array.
 *
 * @param array $array Array (by reference)
 * @param mixed $value New element
 * @param int $offset Position
 * @return int
 */
function array_insert(&$array, $value, $offset)
{
    if (
is_array($array)) {
       
$array  = array_values($array);
       
$offset = intval($offset);
        if (
$offset < 0 || $offset >= count($array)) {
           
array_push($array, $value);
        } elseif (
$offset == 0) {
           
array_unshift($array, $value);
        } else {
           
$temp  = array_slice($array, 0, $offset);
           
array_push($temp, $value);
           
$array = array_slice($array, $offset);
           
$array = array_merge($temp, $array);
        }
    } else {
       
$array = array($value);
    }
    return
count($array);
}

?>
sergei at gmx dot net
04-Oct-2007 03:49
You can preserve keys and unshift an array with numerical indexes in a really simple way if you'll do the following:

$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'
);
mightye at gmail dot com
10-Aug-2007 12:38
@John Brooking:
Better performing would most likely be array_values($input)
amschroeder at gmail dot com
26-Mar-2007 05:13
This becomes a nice little problem if you index your arrays out of order (while manually sorting).  For example:

$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
03-Jun-2006 01: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:

   array_unshift( $myArray, array_shift( $myArray ));
07-Nov-2005 07:38
function multi_array_search($search_value, $the_array)
{
   if (is_array($the_array))
   {
       foreach ($the_array as $key => $value)
       {
           $result = multi_array_search($search_value, $value);
           if (is_array($result))
           {
               $return = $result;
               array_unshift($return, $key);
               return $return;
           }
           elseif ($result == true)
           {
               $return[] = $key;
               return $return;
           }
       }
       return false;
   }
   else
   {
       if ($search_value == $the_array)
       {
           return true;
       }
       else return false;
   }
}
php at electricsurfer dot com
27-Feb-2004 02: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 12: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 07: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
31-Jul-2002 02: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.
TimHyde at C21Technology dot com
18-Jul-2002 12:04
A simpler way to implement an array_unshift with key=>value pairs (i.e. similar to the example using array_reverse above) is to use array_merge.  i.e.

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

Obviously you need to take care when adding numeric or duplicate keys.
jrh_at_geodata.soton.ac.uk
10-Jul-2002 04:30
I have found array_unshift is a function that should be avoided when unshifting lots of data in large arrays.

In a recent script I wrote, it took approx. 24 seconds to unshift 3500 timestamps to an array, a work around could be to use array_reverse and array_push. Array_push is much faster due to the indexing.
robert dot wills at fuzzbrain dot uklinux dot net
07-Feb-2002 02: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 07: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);
}
?>
matt at synergie dot net
19-Sep-2000 05:20
The behaviour of unshift nearly caught me out.
Not only is the item added at the start of the list but the list is re-indexed too.

<?php

$a
= array(5=>"five", 6 =>"six", 20 => "twenty");

while(list(
$key, $value) = each($a))
    echo
"k: $key v: $value<BR>\n";

echo
"<BR>\n";
array_unshift($a, "zero");


while(list(
$key, $value) = each($a))
    echo
"k: $key v: $value<BR>\n";

?>

k: 5 v: five
k: 6 v: six
k: 20 v: twenty

k: 0 v: zero
k: 1 v: five
k: 2 v: six
k: 3 v: twenty

array_values> <array_unique
Last updated: Fri, 30 Oct 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites