★ wanayoo — archive 1999 http://fr.php.net/manual/ja/function.array-push.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<array_poparray_rand>
view the version of this page
Last updated: Wed, 09 Mar 2005

array_push

(PHP 4 , PHP 5)

array_push -- 一つ以上の要素を配列の最後に追加する

説明

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

array_push()は、array をスタックとして処理し、渡された変数を arrayの最後に加えます。配列 arrayの長さは渡された変数の数だけ増加します。 各var毎に以下を繰り返すことと同じ効果があります。
<?php
$array
[] = $var;
?>
varで繰り返されます。

処理後の配列の中の要素の数を返します。

例 1. array_push()の例

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

この例では$stackは次のような要素を 持つようになります:

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

array_pop(), array_shift(), array_unshift()も参照してください。



add a note add a note User Contributed Notes
array_push
josh at digitalfruition dot com
14-Feb-2005 07:17
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 at cgipro dot com
03-Feb-2005 12:18
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
24-Feb-2004 11:48
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
21-Jan-2004 01:05
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();
daijoubuNOSP at Mvideotron dot ca
29-Nov-2003 05:44
If you're only pushing one element, $array[] seems to be a bit faster

<?php
$array
= array();
array_push ($array, 'foo');
?>

VS

<?php
$array
[] = 'foo';
?>
ryan at sinn dot org
12-Nov-2003 04:18
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.":<br>"
  
print_r($$arrayName);
   print
"<br><br>";
?>
daevid at daevid dot com
14-Mar-2003 03:52
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;
}
?>
daevid at daevid dot com
17-Feb-2003 05:38
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);
?>
be at my dot net dot sg
16-Feb-2003 09:35
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
anton at titov dot net
22-Jan-2003 04:23
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);
?>
jhall at jadeinternet dot net
17-Dec-2002 04:34
[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
)
rickf at transpect dot net
06-Nov-2002 02:45
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;
}
?>
daniel at nomail dot com
14-Apr-2002 04:17
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.
Static
04-Feb-2002 09:19
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.
bart at framers dot nl
27-Sep-2001 01:16
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");
?>
misc dot anders at feder dot dk
03-Feb-2001 06:43
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.

<array_poparray_rand>
 Last updated: Wed, 09 Mar 2005
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Fri Mar 18 05:13:58 2005 CET