数组 函数
在线手册:中文  英文

array_push

(PHP 4, PHP 5)

array_push 将一个或多个单元压入数组的末尾(入栈)

说明

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

array_push()array 当成一个栈,并将传入的变量压入 array 的末尾。array 的长度将根据入栈变量的数目增加。和如下效果相同:

<?php
$array
[] = $var;
?>
并对每个 var 重复以上动作。

Note: 如果用 array_push() 来给数组增加一个单元,还不如用 $array[] = ,因为这样没有调用函数的额外负担。

Note: 如果第一个参数不是数组, array_push() 将发出一条警告。这和 $var[] 的行为不同,后者会新建一个数组。

参数

array

输入的数组。

var

要压入的值。

返回值

Returns the new number of elements in the array.

范例

Example #1 array_push() 例子

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

以上例程会输出:

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

参见


数组 函数
在线手册:中文  英文

用户评论:

hacfi (2013-07-03 02:57:28)

I noticed that under certain circumstances it can be faster to use

 <?php
call_user_func_array
("array_push", array('x' => &$array1) + array_values($array2));
 
?>

than

 <?php
foreach ($array2 as $key => $value) {
    
$array1[] = $value;
}
 
?>

chris lanx (2013-06-11 00:07:13)

i wanted to do some string manipulation on a specific field from an sql result set and then append the row to the end of an array like this.
[0] =>
[one] => [val1]
[two] => [val2]
[three] => [val3]
[four] => [val4]
[0] =>
[one] => [val1]
[two] => [val2]
[three] => [val3]
[four] => [val4]
~I tried array push and couldnt get it sorted, So what i did was this.
while ($row = mysql_fetch_assoc($query)) {

$row['five'] = str_replace('.','',$row['place']);
$results[] = $row;
}
resulting in
[0] =>
[one] => [val1]
[two] => [val2]
[three] => [val3]
[four] => [val4]
[five] => [val5]
[0] =>
[one] => [val1]
[two] => [val2]
[three] => [val3]
[four] => [val4]
[five] => [val5]

Rodrigo de Aquino (2012-03-30 03:24:10)

If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:
$data[$key] = $value;
It is not necessary to use array_push.

Chicna (2012-03-21 10:14:15)

I found a simple way to have an "array_push_array" function, without the references problem when we want to use call_user_func_array(), hope this help :
function array_push_array(array &$array)
{
$numArgs = func_num_args();
if(2 > $numArgs)
{
trigger_error(sprintf('%s: expects at least 2 parameters, %s given', __FUNCTION__, $numArgs), E_USER_WARNING);
return false;
}

$values = func_get_args();
array_shift($values);

foreach($values as $v)
{
if(is_array($v))
{
if(count($v) > 0)
{
foreach($v as $w)
{
$array[] = $w;
}
}
}
else
{
$array[] = $v;
}
}

return count($array);
}

Szorstki (2011-12-27 02:35:35)

With multidimensional arrays it's easy too (somebody posted a sample, but it isn't useful for beginners). Here is a piece of code that should explain everything and much more:

<?php
//two classes of objects which will be in multidimensional array
class Org {
    public 
$name;
    public function 
__construct($name) {
        
$this->name $name;
    }
}
class 
Org2 {
    public 
$name;
    public function 
__construct($name) {
        
$this->name $name;
    }
}

//main array
$arr = array();

//creating first subarray manually
//the subarray name must be like first class above
$arr['Org'] = array();

//creating second subarray for objects of selected class
//in another way
$x=2222;        //only for creating the sample object
$arr[get_class(new Org2("wtf".$x))] = array();

//pushing some new objects to (sub)arrays in (main)array
for ($i=0$i<3$i++) {
    
$org1 = new Org("tst".$i);
    
$org2 = new Org2("wtf".$i);
    
array_push($arr[get_class($org1)], $org1);
    
array_push($arr[get_class($org2)], $org2);
}

//printing everything
foreach ($arr as $key=>$value) {
    
$counter 0;
    echo 
"=====".$key." (key) | value: ".$value."<br/>";
    foreach (
$value as $key2=>$value2) {
        if(
$value2 == null) {
            
//echo "counter: ".$counter." | key: ".$key2;
            
unset($arr[$key][$key2]);
        } else {
            
print_r($value2);
            echo 
" [".$counter."]  [".$key2."]<br/>";
        }
        
$counter++;
    }
}

//the additional, second part
echo "<br/>--------<br/><br/>";
//deleting one of the objects from selected (sub)array
unset($arr['Org'][1]);

//printing everything again (look at the counter values)
foreach ($arr as $key=>$value) {
    
$counter 0;
    echo 
"=====".$key." (key) | value: ".$value."<br/>";
    foreach (
$value as $key2=>$value2) {
        if(
$value2 == null) {
            
//echo "counter: ".$counter." | key: ".$key2;
            
unset($arr[$key][$key2]);
        } else {
            
print_r($value2);
            echo 
" [".$counter."]  [".$key2."]<br/>";
        }
        
$counter++;
    }
}
?>

What we get in browser/console:
=====Org (key) | value: Array
Org Object ( [name] => tst0 ) [0] [0]
Org Object ( [name] => tst1 ) [1] [1]
Org Object ( [name] => tst2 ) [2] [2]
=====Org2 (key) | value: Array
Org2 Object ( [name] => wtf0 ) [0] [0]
Org2 Object ( [name] => wtf1 ) [1] [1]
Org2 Object ( [name] => wtf2 ) [2] [2]

--------

=====Org (key) | value: Array
Org Object ( [name] => tst0 ) [0] [0]
Org Object ( [name] => tst2 ) [1] [2]
=====Org2 (key) | value: Array
Org2 Object ( [name] => wtf0 ) [0] [0]
Org2 Object ( [name] => wtf1 ) [1] [1]
Org2 Object ( [name] => wtf2 ) [2] [2]

yuri (2011-11-30 10:00:25)

If you want to put an element to a specific position in an array, try this function.

<?php

function array_put_to_position(&$array$object$position$name null)
{
        
$count 0;
        
$return = array();
        foreach (
$array as $k => $v
        {   
                
// insert new object
                
if ($count == $position)
                {   
                        if (!
$name$name $count;
                        
$return[$name] = $object;
                        
$inserted true;
                }   
                
// insert old object
                
$return[$k] = $v
                
$count++;
        }   
        if (!
$name$name $count;
        if (!
$inserted$return[$name];
        
$array $return;
        return 
$array;
}
?>

Example :

<?php
$a 
= array(
 
'a' => 'A',
 
'b' => 'B',
 
'c' => 'C',
);
            
print_r($a);
array_put_to_position($a'G'2'g');
print_r($a);

/*
Array
(
    [a] => A
    [b] => B
    [c] => C
)
Array
(
    [a] => A
    [b] => B
    [g] => G
    [c] => C
)
*/
?>

aosojnik at gmail dot com (2009-11-23 02:56:56)

If you want to preserve the keys in the array, use the following:

<?php
function array_pshift(&$array) {
    
$keys array_keys($array);
    
$key array_shift($keys);
    
$element $array[$key];
    unset(
$array[$key]);
    return 
$element;
}
?>

rarioj at gmail dot com (2009-10-04 18:44:57)

This function "Returns the new number of elements in the array."

To find out the last index, use:

<?php
$count 
array_push($array$value);
$last_index array_pop(array_keys($array));
?>

Anonymous (2009-09-20 02:00:52)

If you need to push the elements of an array onto the end of another, simply use array_splice():
array_splice($array, count($array), 0, $otherArray);

helpmepro1 at gmail dot com (2009-01-13 13:43:53)

elegant php array combinations algorithm

<?

//by Shimon Dookin

function get_combinations(&$lists,&$result,$stack=array(),$pos=0)
{
 $list=$lists[$pos];
 if(is_array($list))
  foreach($list as $word)
  {
   array_push($stack,$word);
   if(count($lists)==count($stack))
    $result[]=$stack;
   else
    get_combinations($lists,$result,$stack,$pos+1);
   array_pop($stack);
  }
}

$wordlists= array( array("shimon","doodkin") , array("php programmer","sql programmer","mql metatrader programmer") );

get_combinations($wordlists,$combinations);

echo '<xmp>';
print_r($combinations);

?>

wesleys at opperschaap dot net (2008-10-10 00:58:22)

A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

<?php

function array_push_array(&$arr) {
    
$args func_get_args();
    
array_shift($args);

    if (!
is_array($arr)) {
        
trigger_error(sprintf("%s: Cannot perform push on something that isn't an array!"__FUNCTION__), E_USER_WARNING);
        return 
false;
    }

    foreach(
$args as $v) {
        if (
is_array($v)) {
            if (
count($v) > 0) {
                
array_unshift($v, &$arr);
                
call_user_func_array('array_push',  $v);
            }
        } else {
            
$arr[] = $v;
        }
    }
    return 
count($arr);
}

$arr = array(0);
$arr2  = array(6,7,8);
printf("%s\n"array_push_array($arr, array(),array(1,2,3,4,5), $arr2));
print_r($arr);

# error.. 
$arr "test";
printf("%s\n"array_push_array($arr, array(),array(1,2,3,4,5), $arr2));

?>

willdemaine at gmail dot com (2008-08-07 07:00:09)

If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements that I see all the time:

<?php
class timer
{
        private 
$start;
        private 
$end;

        public function 
timer()
        {
                
$this->start microtime(true);
        }

        public function 
Finish()
        {
                
$this->end microtime(true);
        }

        private function 
GetStart()
        {
                if (isset(
$this->start))
                        return 
$this->start;
                else
                        return 
false;
        }

        private function 
GetEnd()
        {
                if (isset(
$this->end))
                        return 
$this->end;
                else
                        return 
false;
        }

        public function 
GetDiff()
        {
                return 
$this->GetEnd() - $this->GetStart();
        }

        public function 
Reset()
        {
                
$this->start microtime(true);
        }

}

echo 
"Adding 100k elements to array with []\n\n";
$ta = array();
$test = new Timer();
for (
$i 0$i 100000$i++)
{
        
$ta[] = $i;
}
$test->Finish();
echo 
$test->GetDiff();

echo 
"\n\nAdding 100k elements to array with array_push\n\n";
$test->Reset();
for (
$i 0$i 100000$i++)
{
        
array_push($ta,$i);
}
$test->Finish();
echo 
$test->GetDiff();

echo 
"\n\nAdding 100k elements to array with [] 10 per iteration\n\n";
$test->Reset();
for (
$i 0$i 10000$i++)
{
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
}
$test->Finish();
echo 
$test->GetDiff();

echo 
"\n\nAdding 100k elements to array with array_push 10 per iteration\n\n";
$test->Reset();
for (
$i 0$i 10000$i++)
{
        
array_push($ta,$i,$i,$i,$i,$i,$i,$i,$i,$i,$i);
}
$test->Finish();
echo 
$test->GetDiff();
?>

Output

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

0.044686794281006

Adding 100k elements to array with array_push

0.072616100311279

Adding 100k elements to array with [] 10 per iteration

0.034690141677856

Adding 100k elements to array with array_push 10 per iteration

0.023932933807373

bxi at apparoat dot nl (2008-05-23 04:29:36)

I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

<?php
$array 
= array();
for (
$x 1$x <= 100000$x++)
{
    
$array[] = $x;
}
?>
takes 0.0622200965881 seconds

and

<?php
$array 
= array();
for (
$x 1$x <= 100000$x++)
{
    
array_push($array$x);
}
?>
takes 1.63195490837 seconds

so if your not making use of the return value of array_push() its better to use the $array[] way.

Hope this helps someone.

alexander dot williamson at gmail dot com (2008-03-26 16:06:05)

This will work to solve the associative array issues:
$aValues[$key] = $value;
Where $key is a unique identifier and $value is the value to be stored. Since the $key works off a string or number, if you already have a $key with the same value as an existing $key, the element will be overwritten.
e.g.
$aValues["one"] = "value of one";
$aValues["two"] = "different value of two!";
gives:
array([one] => "value of one", [two] => "value of two");
but will be overwritten when using the same key (one):
$aValues["one"] = "value of one";
$aValues["one"] = "different value of two!";
will give:
array([one] => "different value of two!");
3686

darkimmortal at dkimmortal dot com (2008-02-18 11:31:11)

I wrote this function for use with 'latest scores' on a quiz site, but it has many potential uses.

<?php
/**
* @desc array_push and removes elements from the beginning of the array until it is within limit
* @param    array   Array to push on to
* @param    mixed   Passed to array push as 2nd parameter
* @param    int     Limit (default = 10)

* @return   array   New array
*/
function array_push_limit($array,$add,$limit=10){
    
array_push($array$add);    
    do {        
        
array_shift($array);
        
$size=count($array);        
    } while(
$size $limit);
        
    return 
$array;
}
?>
----------
EXAMPLE:
----------
<?php
    $array
=array(1, -523, -6633543);    
    
print_r(array_push_limit($array"HELLO"4));
?>
----------
OUTPUT:
----------
Array
(
    [0] => 33
    [1] => 54
    [2] => 3
    [3] => HELLO
)

rob AT rate for the cure dot com (2007-08-15 09:09:34)

I had a problem with .htaccess and some tricky encrypted paths (for protecting true dir names of images and files) and created this quick function to auto correct paths for the document root using regex and array_diff
<?
function fixPath($path){
        $temp = trim($path);
        $temp = eregi_replace("(\./|\.\./)","/",$temp);
        $temp = eregi_replace("([^/]+(\.htm|\.php))","",$temp);
        if(!eregi($_SERVER['DOCUMENT_ROOT'],$temp,$regs)){
            $partsA = explode("/",substr($temp,0,-1));
            $partsB = explode("/",$_SERVER['DOCUMENT_ROOT']);
            //if the path does not match the dir structure diff the array and reconstruct on the TRUE doc root
            $tHolder = array_diff($partsA,$partsB);
                foreach($tHolder as $k=>$v){
                    array_push($partsB,$v);
                }
                        
            $temp =  implode("/",$partsB)."/";
        }
        return $temp;
    }
$correctPath = fixPath('.som/phpEncrypted/Path/class/class.QMI.php');
?>

The function strips out filename, checks to see if the path resolves to the doc root, and if it does not it takes the difference in the paths and returns a path that translates to the true path. This is useful for encoding paths where you want to obfuscate the true server path (such as creating external api functions)

zbde00 at hotmail dot com (2007-07-20 05:59:31)

A very good function to remove a element from array
function array_del($str,&$array)
{
if (in_array($str,$array)==true)
{

foreach ($array as $key=>$value)
{
if ($value==$str) unset($array[$key]);
}
}
}

antido at gmail dot com (2006-08-03 01:04:52)

Simple data object implementation:

<?php

/**
 * Data object
 * 
 * @version 0.6
 * @author Tom Reitsma <antido@gmail.com>
 */
Class DataObject
{
    
/**
     * @var int $ptr
     */
    
private $ptr 0;
    
    
/**
     * @var array $data
     */
    
private $data = array();
    
    
/**
     * Class constructor
     */
    
public function __construct($anArray=false)
    {
        if(
$anArray != false)
        {
            if(
is_array($anArray))
            {
                
$this->data[] = $anArray;
            }
        }
    }
    
    
/**
     * Fetches the data under the pointer
     * 
     * @return String if there is still data left under the pointer, false if the end has been reached
     */
    
public function fetch()
    {
        if(isset(
$this->data[$this->ptr]))
        {
            return 
$this->data[$this->ptr++];
        }
        
        return 
false;
    }
    
    
/**
     * Moves to the next row in the data object
     * 
     * @return boolean
     */
    
public function moveNext()
    {
        
$newPtr $this->ptr 1;
        
        if(isset(
$this->data[$newPtr]))
        {
            
$this->ptr $newPtr;
            return 
true;
        }
        
        return 
false;
    }
    
    
/**
     * Moves to the previous row in the data object
     * 
     * @return boolean
     */
    
public function movePrevious()
    {
        
$newPtr $this->ptr 1;
        
        if(isset(
$this->data[$newPtr]))
        {
            return 
$this->data[$newPtr];
        }
        
        return 
false;
    }
    
    
/**
     * Pushes an element onto the array
     * 
     * @param String or an array $input
     * @return number of elements
     */
    
public function push($input)
    {
        if(
$this->getNumRows() > 0)
        {
            return 
array_push($this->data$input);
        }
        else 
        {
            return 
$this->data[] = $input;
        }
    }
    
    
/**
     * Counts the number of rows
     */
    
public function getNumRows()
    {
        return 
count($this->data);
    }
}

?>

Marc Bernet (2006-05-15 09:18:01)

A small and basic implementation of a stack without using an array.
class node
{
var $elem;
var $next;
}
class stack
{
var $next;
function pop()
{
$aux=$this->next->elem;
$this->next=$this->next->next;
return $aux;
}
function push($obj)
{
$nod=new node;
$nod->elem=$obj;
$nod->next=$this->next;
$this->next=$nod;
}
function stack()
{
$this->next=NULL;
}
}

richard dot udo at gmail dot com (2006-02-09 03:05:37)

Just a typo i think but the code below will actually produce
Array
(
[0] => a
[1] => b
[2] => c
[3] => Array
(
[0] => d
[1] => e
[2] => f
)
)

egingell at sisna dot com (2006-01-28 06:06:41)

If you push an array onto the stack, PHP will add the whole array to the next element instead of adding the keys and values to the array. If this is not what you want, you're better off using array_merge() or traverse the array you're pushing on and add each element with $stack[$key] = $value.

<?php

$stack 
= array('a''b''c');
array_push($stack, array('d''e''f'));
print_r($stack);

?>
The above will output this:
Array (
  [0] => a
  [1] => b
  [2] => c
  [3] => Array (
     [0] => a
     [1] => b
     [2] => c
  )
)

steve at webthoughts d\ot ca (2005-11-12 16:02:06)

Further Modification on the array_push_associative function
1.  removes seemingly useless array_unshift function that generates php warning
2.  adds support for non-array arguments

<?
// Append associative array elements
function array_push_associative(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
               $ret++;
           }
       }else{
           $arr[$arg] = "";
       }
   }
   return $ret;
}

$items = array("here" => "now");
$moreitems = array("this" => "that");

$theArray = array("where" => "do we go", "here" => "we are today");
echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';
    
echo "<pre>";
print_r($theArray);
echo "</pre>";

?>

Yields: 

4 is the size of $theArray.
Array
(
    [where] => do we go
    [here] => now
    [this] => that
    [five] => 
)

ludvig dot ericson at gmail dot com (2005-10-31 05:32:43)

Previous comment was not fully imitating the array_push behaviour,
1) does not return number of items pushed
2) can only handle one array to push

> Revised associative_push function with absolute reference of arg1 array; left unchanged if arg2 is empty.

<?php
// Append associative array elements
function array_push_associative(&$arr) {
    
$args func_get_args();
    
array_unshift($args); // remove &$arr argument
    
foreach ($args as $arg) {
        if (
is_array($arg)) {
            foreach (
$arg as $key => $value) {
                
$arr[$key] = $value;
                
$ret++;
            }
        }
    }
    
    return 
$ret;
}

$theArray = array();
echo 
array_push_associative($theArray$items$moreitems) . ' items added to $theArray.';
?>

john (2005-10-19 13:33:05)

A variation of kamprettos' associative array push:
// append associative array elements
function associative_push($arr, $tmp) {
if (is_array($tmp)) {
foreach ($tmp as $key => $value) {
$arr[$key] = $value;
}
return $arr;
}
return false;
}
$theArray = array();
$theArray = associative_push($theArray, $items);

kamprettos at yahoo dot com Teguh Iskanto (2005-09-19 05:33:57)

Looking for a way to push data into an associative array and frustrated to know that array_push() can't do the job ? 

here's my Scenario : 
-------------------
I need to relate system command output into an associative array like these :

[sge@digital_db work]$ /usr/local/apache/htdocs/work/qhost.sh -h t1 -F | awk '{if(NR>4) print $1}' | sed  's/hl://g' 
arch=lx24-amd64
num_proc=2.000000
mem_total=3.808G
swap_total=3.907G
virtual_total=7.715G
load_avg=0.000000
load_short=0.000000
load_medium=0.000000
load_long=0.000000
mem_free=3.510G
swap_free=3.907G
virtual_free=7.417G
mem_used=305.242M
swap_used=0.000
virtual_used=305.242M
cpu=0.000000
np_load_avg=0.000000
np_load_short=0.000000
np_load_medium=0.000000
np_load_long=0.000000

how I did it :
<? php

# get into the system command output 
$assoc_cmd =`$work_dir/qhost.sh -h $host_resource -F | awk '{if(NR>4) print $1}'| sed  's/hl://g' ` ;

# split the "\n" character 
$assoc_row = explode("\n", chop($assoc_cmd));

# get the index row 
$idx_row  = count($assoc_row) - 1 ;

# initialize the associative array 
$host_res_array = array();

for ($i = 0 ; $i<= $idx_row ; $i++) 
        {       
                # get params & values 
                list($host_param,$host_val) = explode("=",$assoc_row[$i]);

                # populate / push data to assoc array 
                $host_res_array[$host_param]= $host_val ;
        }    

echo "<pre> Architecture : </pre>\n" ;
echo $host_res_array['arch'] ;
echo "<pre> Mem Total    : </pre>\n" ;
echo $host_res_array['mem_tot'];

?>

Hope this helps ! :)

bk at quicknet dot nl (2005-09-04 01:51:17)

Add elements to an array before or after a specific index or key:

<?php

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_before($src,$in,$pos){
    if(
is_int($pos)) $R=array_merge(array_slice($src,0,$pos), $inarray_slice($src,$pos));
    else{
        foreach(
$src as $k=>$v){
            if(
$k==$pos)$R=array_merge($R,$in);
            
$R[$k]=$v;
        }
    }return 
$R;
}

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_after($src,$in,$pos){
    if(
is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $inarray_slice($src,$pos+1));
    else{
        foreach(
$src as $k=>$v){
            
$R[$k]=$v;
            if(
$k==$pos)$R=array_merge($R,$in);
        }
    }return 
$R;
}

// Examples:

$src=array("A","B","C");
$in=array("X","Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "X"
  [2]=>
  string(1) "Y"
  [3]=>
  string(1) "B"
  [4]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "X"
  [3]=>
  string(1) "Y"
  [4]=>
  string(1) "C"
}*/

$src=array('a'=>"A",'b'=>"B",'c'=>"C");
$in=array('x'=>"X",'y'=>"Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, key array, before index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_before($src,$in,'b'));
/* array_push_before, key array, before key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, key array, after index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,'b'));
/* array_push_after, key array, after key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

?>

ciprian dot amariei at gmail com (2005-08-30 14:47:51)

regarding the speed of oneill's solution to insert a value into a non-associative array, I've done some tests and I found that it behaves well if you have a small array and more insertions, but for a huge array and a little insersions I sugest using this function:
function array_insert( &$array, $index, $value ) {
$cnt = count($array);

for( $i = $cnt-1; $i >= $index; --$i ) {
$array[ $i + 1 ] = $array[ $i ];
}
$array[$index] = $value;
}
or if you are a speed adicted programmer (same situation: big array, few insertions) use this:
array_splice ( $array, $offset, 0, $item );
item may also be an array of values ;).

Phil Davies (2005-07-18 03:51:09)

As someone pointed out the array_push() function returns the count of the array not the key of the new element. As it was the latter function i required i wrote this very simple replacement.
function array_push2(&$array,$object,$key=null){
$keys = array_keys($array);
rsort($keys);
$newkey = ($key==null)?$keys[0]+1:$key;
$array[$newkey] = $object;
return $newkey;
}

oneill at c dot dk (2005-06-03 13:50:32)

To insert a value into a non-associative array, I find this simple function does the trick:
function insert_in_array_pos($array, $pos, $value)
{
$result = array_merge(array_slice($array, 0 , $pos), array($value), array_slice($array, $pos));
return $result;
}
Seems an awful lot simpler than the iterative solutions given above...

aaron dot hawley at uvm dot edu (2005-05-27 11:36:42)

Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does. There's another difference between array_push and the recommended empty bracket notation.
Empy bracket doesn't check if a variable is an array first as array_push does. If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.
So array_push is safer than [], until further this is changed by the PHP developers.

josh at digitalfruition dot com (2005-02-14 10:17:27)

Note that array_push() will, as described, return the COUNT of the array after adding a new item, not necessarily the INDEX of that new item:

<?php
$array 
= array(=> 'three'=> 'five');

echo 
"\$array = ";
print_r($array);
echo 
"\n\n";

$to_push = array(1,2,4,);
foreach(
$to_push as $var)
{
    echo 
"calling array_push(\$array,$var); retval is ";
    echo 
array_push($array,$var);
    echo 
"\n";
}

echo 
"\$array = ";
print_r($array);
?>

The output of above is:

$array = Array
(
    [3] => three
    [5] => five
)

calling array_push($array,1); retval is 4
calling array_push($array,2); retval is 5
calling array_push($array,4); retval is 6
$array = Array
(
    [3] => three
    [5] => five
    [7] => seven
    [8] => 1
    [9] => 2
    [10] => 4
)

Notice how when array_push($array,1) was called, the new element has a key of 8 but array_push() returns 4.

andrew at cgipro dot com (2005-02-02 15:18:51)

Need a real one-liner for adding an element onto a new array name?
$emp_list_bic = $emp_list + array(c=>"ANY CLIENT");
CONTEXT...
drewdeal: this turns out to be better and easier than array_push()
patelbhadresh: great!... so u discover new idea...
drewdeal: because you can't do: $emp_list_bic = array_push($emp_list, c=>"ANY CLIENT");
drewdeal: array_push returns a count and affects current array.. and does not support set keys!
drewdeal: yeah. My one-liner makes a new array as a derivative of the prior array

aron (2004-02-24 02:48:22)

The problem with array_push is that it is pass by value.  If you are dealing with objects whose inner state may change at any time, you need a push and pop who return the actual objects, rather than copies of them.  
After some difficulty and board assistance, I have these methods.  I've tested them, and they seem to work fine.

<?php
function push(&$array, &$object){    
    
$array[] =& $object;    
}
function & 
pop(&$array){
    return 
array_pop($array);
}

// [Test Code]
class TestObject{
    var 
$value 0;
    function 
getValue(){
        return 
$this->value;
    }
    function 
setValue($mixed){
        
$this->value $mixed;
    }
}
$myarr = array();
$tmp =& new TestObject();
$tmp2 =& new TestObject();
$tmp->setValue(2);
$tmp2->setValue(3);

push($myarr$tmp);
push($myarr$tmp2);
$tmp->setValue(4);
$tmp2->setValue(6);
$val pop($myarr);
print 
"popped value: ".$val->getValue()."<br />";

print 
"values in internal array: <br />";
foreach (
$myarr as $key=>$value){
    print 
"key: $key, object: $value, value: ";
    print  
$value->getValue()."<br />";
}
// [/TestCode]
?>

skiflyer (2004-01-20 16:05:07)

However, don't forget that array_push() does more than [], it also performs a count and returns the value.
Modifying your code ever so slightly (see below), this puts array_push in the lead (not suprisingly). So my conclusion would be that if I care about the number of elements in the array, then I'd use array_push(), if I don't (which is usually the case), then I'd use the [] method.
Results...
[] method: 0.34943199
push method: 0.31505919
difference: -0.03437280
Modified section of code...
$s_test_begin = FullMicroTime();
for($i = 0; $i <= 50000; $i++) { $num_tot = array_push($test2, $i); }
$s_test_end = FullMicroTime();
$f_test_begin = FullMicroTime();
for($i = 0; $i <= 50000; $i++) { $test[] = $i; $num_tot = count($test); }
$f_test_end = FullMicroTime();

daevid at daevid dot com (2003-02-16 20:38:20)

Sadly, array_push() does not create an array if the array doesn't exist.  So if you're pushing the first element onto an array, you need to check and create it manually...

<?php
if ( !is_array($myArray) ) $myArray= array();
array_push($myArray$myElement);
?>

bart at framers dot nl (2001-09-27 04:16:10)

Array_push also works fine with multidimensional arrays. Just make sure the element is defined as an array first.

<?php
$array
["element"][$element]["element"] = array();
array_push ($array["element"][$element]["element"], "banana");
?>

易百教程