Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_push

array_push

Push one or more elements onto the end of array (PHP 4, PHP 5)
int array_push ( array &array, mixed var [, mixed ...] )

Example 271. array_push() example

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

The above example will output:

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

Related Examples ( Source code ) » array_push









Code Examples / Notes » array_push

jhall

[Editors Note:
See http://www.php.net/array_splice for a function that does the same thing.]
I needed a function to add data to a particular place in an array without loosing any other data in the array. Here it is:
<?php
function insert_into_array($array,$ky,$val)
{
$n = $ky;
foreach($array as $key => $value)
  {
    $backup_array[$key] = $array[$key];
  }
$upper_limit = count($array);
while($n <= $upper_limit)
  {
    if($n == $ky)
      {
$array[$n] = $val;
echo $n;
      }
    else
      {
$i = $n - "1";
$array[$n] = $backup_array[$i];
      }
    $n++;
  }
return $array;
}
?>
So that:
<?php
$list = array( "0" => "zero",
      "1" => "one",
      "2" => "two",
      "3" => "three",
      "4" => "four",
      "5" => "five",
      "6" => "six");
$value = "New Number Three";
$key = "3";
$new = insert_into_array($list,$key, $value);
?>
Will Return:
$list =
Array
(
   [0] => zero
   [1] => one
   [2] => two
   [3] => three
   [4] => four
   [5] => five
   [6] => six
)
$new=
Array
(
   [0] => zero
   [1] => one
   [2] => two
   [3] => New Number Three
   [4] => three
   [5] => four
   [6] => five
   [7] => six
)


ryan

You can merge key and value combinations into "variable variable" arrays using {} around the variable name.
Here's an example:
<?php
   $arrayName = time();
   ${$arrayName}["mykey"] = "myvalue";
   print $arrayName.":
"
   print_r($$arrayName);
   print "
";
?>


oneill

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...


aron

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]
?>


misc dot anders

The $array[] = $var statement differs from array_push($array, $var) in that it can operate on uninitialized variables as well. array_push only works with initialized arrays.

aaron dot hawley

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.


antido

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


daevid

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


ciprian dot amariei

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


ludvig dot ericson

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.';
?>


josh

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(3 => 'three', 5 => '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

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


kamprettos

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 ! :)


daevid

Just to fix and clean up the above example... it should be:
<?php
function addArray(&$array, $key, $val)
{
$tempArray = array($key => $val);
$array = array_merge ($array, $tempArray);
}
?>
and use this to view them:
<?php
foreach ($myArray as $key=>$val)
{
echo "key = ".$key." val = ".$val;
}
?>


richard dot udo

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


daniel

If you want to use integer keys simply treat it as an 'ordinary' array.
<?php
$user_arr = array();
$user_id = 4;
$user_name = 'John';
$user_arr[$user_id] = $user_name;
$user_id = 346;
$user_name = 'Steve';
$user_arr[$user_id] = $user_name;
$user_id = 652;
$user_name = 'Maria';
$user_arr[$user_id] = $user_name;
?>
All slots in between the three user IDs will not be allocated and sizeof($user_arr) will return 3 and not 653.


egingell

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


static

I noticed that when building a large array, array_push($array, $value) didn't seem to be quite as fast as $array[] = $value. Using the latter would therefore be a useul optimisation if you can guarantee unique keys (e.g. reading from a DB table with an id field).
Static.


rob

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)


skiflyer

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


be

Here's a function to add any key variable into array. this function cannot be use if the key and var set are both numbers.
<?php
function addArray(&$array, $id, $var)
{
$tempArray = array($var => $id);
$array = array_merge ($array, $tempArray);
}
$myArray= array ();
addArray($myArray, 1, 'something');
?>
Displaying:
<?php
foreach (array_keys($myArray) as $fields)
{
print $myArray[$fields];
print $fields;
}
?>
Result:
1
something


krristaps

Here is the smallest chunk of php code describing data structure called stack:
<?php
class stack{
       var $memory=array();
       function push($value){
               $this->memory[]=$value;
       }
       function pop(){
               $count=$this->count();
               if ($count){
                       $value=$this->memory[$count-1];
                       unset($this->memory[$count-1]);
                       return $value;
               }
               else return false;
       }
       function count(){
               return count($this->memory);
       }
};
?>


steve

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] =>
)


anton

For the note above: you can use array_splice function to insert a new value (or array) in the middle of array, this will work like your code does:
<?php
$list = array(
     "0" => "zero",
     "1" => "one",
     "2" => "two",
     "3" => "three",
     "4" => "four",
     "5" => "five",
     "6" => "six"
);
$value = "New Number Three";
$key = "3";
$new = array_splice($list, $key, 0, $value);
?>


phil davies

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


bart

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


rickf

Another associative array sorter. Will handle null arrays, and should correctly handle multidimensionals. Essentially, it pulls all the keys into an array, randomizes that array, then spits out a reconstructed array based on the randomized keys.
I would have used array_keys() instead of the first foreach(), but unfortunately the array returned gets spit back in hash order, not array order. My particular needs required me to have reproducable randomizations based on specific mt_srand() values. For most people who just need a random array output with no reproduction, you can substitute the line beneath.
<?php
function assocArrayShuffle($inarray) {
       if(!$inarray) return $inarray;
       $keys = array(); $rkeys = array();
       foreach($inarray as $k => $v) $keys[] = $k;
       // OR... $keys = array_keys();
       while(count($keys)>0) {
               list($k) = array_splice($keys, mt_rand(0, count($keys)-1), 1);
               $rkeys[] = $k;
       }
       foreach($rkeys as $k => $v) $outarray[$v] = $inarray[$v];
       return $outarray;
}
?>


bk

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), $in, array_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), $in, array_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"
}*/
?>


zbde00

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]);
}
}
}


john

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


marc bernet

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


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker