array_push
(PHP 4, PHP 5, PHP 7, PHP 8)
array_push — 一つ以上の要素を配列の最後に追加する
説明
array_push()は、array
をスタックとして処理し、渡された変数を
array
の最後に加えます。配列
array
の長さは渡された変数の数だけ増加します。
各 value1
毎に以下を繰り返すことと同じ効果があります。
<?php
$array[] = $var;
?>
value1
で繰り返されます。
注意: もし配列にひとつの要素を加えるために array_push() を使用するなら、 関数を呼ぶオーバーヘッドがないので、
$array[] =
を使用するほうがいいです。
注意: 最初の引数が配列でない場合、array_push() は警告を発生させます。これは、PHP 7.1.0 より前のバージョンの、 新規配列を生成する場合における
$var[]
の動作と異なっていました。
パラメータ
array
-
入力の配列。
values
-
array
の最後に追加する値。
戻り値
処理後の配列の中の要素の数を返します。
変更履歴
バージョン | 説明 |
---|---|
7.3.0 | この関数は、1 つのパラメータでのみ呼び出すことができるようになりました。 前は、少なくとも 2 つのパラメータが必要でした。 |
例
例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 )
参考
- array_pop() - 配列の末尾から要素を取り除く
- array_shift() - 配列の先頭から要素を一つ取り出す
- array_unshift() - 一つ以上の要素を配列の最初に加える
+add a note
User Contributed Notes 35 notes
Rodrigo de Aquino ¶
12 years ago
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.
bxi at apparoat dot nl ¶
16 years ago
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.
mrgreen dot webpost at gmail dot com ¶
8 years ago
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 < 5; $i++ ) {
$data += [ "element$i" => $i ];
}
...which will result in an array that looks like this...
[ "element1" => 1, "element2" => 2, "element3" => 3, "element4" => 4 ]
willdemaine at gmail dot com ¶
16 years ago
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
yhusky at qq dot com ¶
6 years ago
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".
<?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] => d
[1] => e
[2] => f
)
)
raat1979 at gmail dot com ¶
8 years ago
Unfortunately array_push returns the new number of items in the array
It does not give you the key of the item you just added, in numeric arrays you could do -1, you do however need to be sure that no associative key exists as that would break the assumption
It would have been better if array_push would have returned the key of the item just added like the below function
(perhaps a native variant would be a good idea...)
<?php
if(!function_exists('array_add')){
function array_add(array &$array,$value /*[, $...]*/){
$values = func_get_args(); //get all values
$values[0]= &$array; //REFERENCE!
$org=key($array); //where are we?
call_user_func_array('array_push',$values);
end($array); // move to the last item
$key = key($array); //get the key of the last item
if($org===null){
//was at eof, added something, move to it
return $key;
}elseif($org<(count($array)/2)){ //somewhere in the middle +/- is fine
reset($array);
while (key($array) !== $org) next($List);
}else{
while (key($array) !== $org) prev($List);
}
return $key;
}
}
echo "<pre>\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "Taken array;";
print_r($pr);
echo "\npush 1 returns ".array_push($pr,1)."\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\npush 2 returns ".array_push($pr,1,2)."\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\n add 1 returns ".array_add($pr,2)."\n\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\n add 2 returns ".array_add($pr,1,2)."\n\n";
echo "<pre/>\n\n";
?>
Outputs:
Taken array;Array
(
[foo] => bar
[bar] => foo
)
push 1 returns 3
------------------------------------
push 2 returns 4
------------------------------------
add 1 returns 0
------------------------------------
add 2 returns 1
egingell at sisna dot com ¶
18 years ago
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
)
)
Carlos Alberto B. Carucce ¶
5 years ago
This is how I add all the elements from one array to another:
<?php
$oneArray = ['d', 'e', 'f'];
$anotherArray = ['a', 'b', 'c'];
array_push($anotherArray, ...$oneArray);
//['a', 'b', 'c', 'd', 'e', 'f'];
P.A.Semi ¶
5 years ago
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 ...
aosojnik at gmail dot com ¶
14 years ago
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;
}
?>
helpmepro1 at gmail dot com ¶
15 years ago
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);
?>
colecooper2005 at icloud dot com ¶
7 years ago
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);
aaron dot hawley at uvm dot edu ¶
19 years ago
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.
andrew at cgipro dot com ¶
19 years ago
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
gfuente at garrahan dot gov dot ar ¶
7 years ago
If the element to be pushed onto the end of array is an array you will receive the following error message:
Unknown Error, value: [8] Array to string conversion
I tried both: (and works, but with the warning message)
$aRol = array( $row[0], $row[1], $row[2] );
$aRoles[] = $aRol;
and
array_push( $aRoles, $aRol);
The correct way:
$cUnRol = implode("(",array( $row[0], $row[1], $row[2] ) );
array_push( $aRoles, $cUnRol );
thanks.
steve at webthoughts d\ot ca ¶
18 years ago
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] =>
)
flobee ¶
10 years ago
Be warned using $array "+=" array(1,2,3) or union operations (http://php.net/manual/en/language.operators.array.php)
I think it worked in the past or i havent test it good enough. :-/
(once it worked, once [] was faster than array_push, the past :-D ):
php -r '$a = array(1,2); $a += array(3,4); print_r($a);'
Array (
[0] => 1
[1] => 2
)
php -r '$a = array(1,2); $b = array(3,4);$c = $a + $b; print_r($c);'
Array (
[0] => 1
[1] => 2
)
php -r '$a = array(1,2); $b = array(2=>3,3=>4);$c = $a + $b; print_r($c);'
Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
David Spector ¶
3 years ago
After using array_push you may wish to read the top (last) array element one or more times before using array_pop. To read the top array element efficiently, use the 'current' function.
siqueiramoises14 at gmail dot com ¶
5 years ago
if you need to push a multidimensional numeric array into another, array push will push the hole array into a key of the first array, for example, let's imagine you have two arrays:
<?php
$array1 = [
0 => [
"key1" => "value1",
"key2" => "value2"
]
];
$array2 = [
0 => [
"key1" => "value1",
"key2" => "value2"
]
];
$array1[] = $array2;
//after that array1 will look like this:
[
0 => [
"key1" => "value1",
"key2" => "value2"
],
1 => [
0 => [
"key1" => "value2",
"key2" => "value2"
]
]
// If you don't want that to happen here's a function to avoid that:
function array_push_indexes($array1, $array2){
$lastKey = array_key_last($array1);
for($i = 0; $i < count($array2); $i++){
$KeyPosition = 1 + $i;
$array1[$lastKey+$KeyPosition] = $array2[$i];
}
return $array1;
}
//Using the same example from before this function will return:
[
0 => [
"key1" => "value1",
"key2" => "value2"
],
1 => [
"key1" => "value1",
"key2" => "value2"
]
]
?>
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
wesleys at opperschaap dot net ¶
16 years ago
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));
?>
bk at quicknet dot nl ¶
19 years ago
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"
}*/
?>
golddragon007 ¶
9 years ago
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 <= 100000; $x++)
{
$array[] = $x;
}
$endTime = microtime(true);
// Case 2
$startTime = microtime(true);
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
array_push($array, $x);
}
$endTime = microtime(true);
// Case 3
$result = array();
$array2 = array(&$result)+$array;
$startTime = microtime(true);
call_user_func_array("array_push", $array2);
$endTime = microtime(true);
// Case 4
$result = array();
for ($x = 1; $x <= 100000; $x++)
{
$result[] = $x;
}
$array2 = array(&$result)+$array;
$startTime = microtime(true);
call_user_func_array("array_push", $array2);
$endTime = microtime(true);
// Case 5
$result = array();
$startTime = microtime(true);
$array = array(&$result);
for ($x = 1; $x <= 100000; $x++)
{
$array[] = $x;
}
$endTime = microtime(true);
// Case 6
$result = array(1,2,3,4,5,6);
$startTime = microtime(true);
$array = array(&$result);
for ($x = 1; $x <= 100000; $x++)
{
$array[] = $x;
}
$endTime = microtime(true);
// Case 7
$result = array();
for ($x = 1; $x <= 100000; $x++)
{
$result[] = $x;
}
$startTime = microtime(true);
$array = array(&$result);
for ($x = 1; $x <= 100000; $x++)
{
$array[] = $x;
}
$endTime = microtime(true);
Marc Bernet ¶
18 years ago
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;
}
}
oneill at c dot dk ¶
19 years ago
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...
yuri ¶
12 years ago
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
)
*/
?>
alexander dot williamson at gmail dot com ¶
16 years ago
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
zbde00 at hotmail dot com ¶
17 years ago
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]);
}
}
}
Chicna ¶
12 years ago
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);
}