百科狗-知识改变命运!
--

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

乐乐11个月前 (11-21)阅读数 16#技术干货
文章标签数组

array_push()

(PHP 4, PHP 5, PHP 7)

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

说明

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

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

并对每个传入的值重复以上动作。

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

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

参数

$array

输入的数组。

$value1

要压入$array末尾的第一个值。

返回值

返回处理之后数组的元素个数。

范例

Example #1array_push()例子

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

以上例程会输出:

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

参见

  • array_pop() 弹出数组最后一个单元(出栈)
  • array_shift() 将数组开头的单元移出数组
  • array_unshift() 在数组开头插入一个或多个单元
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.
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

takes 0.0622200965881 seconds
and

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.
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do...
    $data[$key] = $value;
...but this is actually not true. Unlike array_push and even...
    $data[] = $value;
...Rodrigo's suggestion is NOT guaranteed to append the new element to the END of the array. For instance...
    $data['one'] = 1;
    $data['two'] = 2;
    $data['three'] = 3;
    $data['four'] = 4;
 
...might very well result in an array that looks like this...
    [ "four" => 4, "one" => 1, "three" => 3, "two" => 2 ]
I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won't matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.
If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead...
    $data['one'] = 1;
    $data += [ "two" => 2 ];
    $data += [ "three" => 3 ];
    $data += [ "four" => 4 ];
You can also, of course, append more than one element at once...
    $data['one'] = 1;
    $data += [ "two" => 2, "three" => 3 ];
    $data += [ "four" => 4 ];
Note that like array_push (but unlike $array[] =) the array must exist before the unary union, which means that if you are building an array in a loop you need to declare an empty array first...
    $data = [];
    for ( $i = 1; $i  $i ];
    }
...which will result in an array that looks like this...
   [ "element1" => 1, "element2" => 2, "element3" => 3, "element4" => 4 ]
There is a mistake in the note by egingell at sisna dot com 12 years ago. The tow dimensional array will output "d,e,f", not "a,b,c".

The above will output this:
Array (
 [0] => a
 [1] => b
 [2] => c
 [3] => Array (
   [0] => d
   [1] => e
   [2] => f
 )
)
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:

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

The above will output this:
Array (
 [0] => a
 [1] => b
 [2] => c
 [3] => Array (
   [0] => a
   [1] => b
   [2] => c
 )
)
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
I did a performance check, and I saw, if you push more than one value it can be faster the array push, that the normal $array[] version.
Case 1: $array[] = something;
Case 2: array_push($array, $value);
Case 3: array_push($array, $value1, $value2, $value3 [...]); $values are definied
Case 4: array_push($array, $value1, $value2, $value3 [...]); $values are definied, when $array is not empty
Case 5: Case1 + Case 3
Case 6: Result array contains some value (Case 4)
Case 7: Result array contains same value as the push array (Case 4)
-----------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~ Case 1 ~~~~~~~~~~~~
Times: 0.0310 0.0300 0.0290 0.0340 0.0400 0.0440 0.0480 0.0550 0.0570 0.0570
Min: 0.0290
Max: 0.0570
Avg: 0.0425
~~~~~~~~~~~~ Case 2 ~~~~~~~~~~~~
Times: 0.3890 0.3850 0.3770 0.4110 0.4020 0.3980 0.4020 0.4060 0.4130 0.4200
Min: 0.3770
Max: 0.4200
Avg: 0.4003
~~~~~~~~~~~~ Case 3 ~~~~~~~~~~~~
Times: 0.0200 0.0220 0.0240 0.0340 0.0360 0.0410 0.0460 0.0500 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0377
~~~~~~~~~~~~ Case 4 ~~~~~~~~~~~~
Times: 0.0200 0.0250 0.0230 0.0260 0.0330 0.0390 0.0460 0.0510 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0367
~~~~~~~~~~~~ Case 5 ~~~~~~~~~~~~
Times: 0.0260 0.0250 0.0370 0.0360 0.0390 0.0440 0.0510 0.0520 0.0530 0.0560
Min: 0.0250
Max: 0.0560
Avg: 0.0419
~~~~~~~~~~~~ Case 6 ~~~~~~~~~~~~
Times: 0.0340 0.0280 0.0370 0.0410 0.0450 0.0480 0.0560 0.0580 0.0580 0.0570
Min: 0.0280
Max: 0.0580
Avg: 0.0462
~~~~~~~~~~~~ Case 7 ~~~~~~~~~~~~
Times: 0.0290 0.0270 0.0350 0.0410 0.0430 0.0470 0.0540 0.0540 0.0550 0.0550
Min: 0.0270
Max: 0.0550
Avg: 0.044
Tester code:
// Case 1
  $startTime = microtime(true);
  $array = array();
  for ($x = 1; $x 
P.S: the array_key_last function it's for PHP >= 7.3.0 see more here https://www.php.net/manual/en/function.array-key-last.php
There is problem with pushing references to array, introduced in PHP 5.4 - did someone decide it is not needed?
In PHP 5.3 this could be used:
$A=array(); array_push($A,1); $c=2; array_push($A,&$c); print_r($A); $c=3; print_r($A);
Outputs correctly:
Array ( [0] => 1 [1] => 2 )
Array ( [0] => 1 [1] => 3 )
Think of Reference as a pointer in other languages...
This function is needed for example to push parameters for MySql query:
$params=array(); array_push($params,&$field1); array_push($params,&$field2); array_unshift($params,'ss');
call_user_func_array(array($Query,'bind_param'),$params);
This code causes fatal error in PHP 5.4 and depending on server configuration it may not even be reported why...
A workarround to allow pushing references to array is this:
$A=array(); $A[]=1; $c=2; $A[]=&$c; print_r($A); $c=3; print_r($A);
$params=array(); $params[]=&$field1; $params[]=&$field2; array_unshift($params,'ss');
call_user_func_array(array($Query,'bind_param'),$params);
(in actual code, the fields are specified dynamically and iterated in for-loop...)
This seems working both on PHP 5.3 and PHP 5.6 ...
Add elements to an array before or after a specific index or key: 
When developing a pocketmine plugin, a good way to add stuff to a YAML table is
$table=$this->config->get("Table");
array_push($table, "New Value for table");
$this->config->set("Table", $table);
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.
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)