Php array add key value pair to existing array

Im trying to add a key=>value to a existing array with a specific value.

Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:

ex:

[0] => Array
    [
        [id] => 1
        [blah] => value2

    ]

[1] => Array
    [
        [id] => 1
        [blah] => value2
    ]

I want to do it so that while

foreach [$array as $arr] {

     while $arr['id']==$some_id {

            $array['new_key'] .=$some value
            then do a array_push
      }    
}

so $some_value is going to be associated with the specific id.

Joseph Silber

208k57 gold badges356 silver badges288 bronze badges

asked Jul 12, 2012 at 22:40

0

The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:

$tmp = new array[];
foreach [$array as $arr] {

     if[$array['id']==$some_id] {
            $tmp['new_key'] = $some_value;
      }    
}


array_merge[$array,$tmp];

A more efficient way is this:

if[in_array[$some_id,$array]{
  $array['new_key'] = $some_value;
}

or if its a key in the array you want to match and not the value...

if[array_key_exists[$some_id,$array]{
      $array['new_key'] = $some_value;
    }

answered Jul 12, 2012 at 22:46

TuckerTucker

6,8079 gold badges36 silver badges55 bronze badges

1

When you use:

foreach[$array as $arr]{
    ...
}

... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:

foreach[$array as &$arr]{ // notice the &
    ...
}

... now if you add a new key to that array it will affect the $array through which you are looping.

I hope I understood your question correctly.

answered Jun 24, 2013 at 20:59

If i understood you correctly, this will be the solution:

foreach [$array as $arr] {
  if [$arr['id'] == $some_id] {
     $arr[] = $some value;
     // or: $arr['key'] but when 'key' already exists it will be overwritten
  }
}

answered Jul 12, 2012 at 22:46

BesnikBesnik

6,3031 gold badge30 silver badges32 bronze badges

[PHP 4, PHP 5, PHP 7, PHP 8]

array_pushPush one or more elements onto the end of array

Description

array_push[array &$array, mixed ...$values]: int

repeated for each passed value.

Note: If you use array_push[] to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

Note: array_push[] will raise a warning if the first argument is not an array. This differed from the $var[] behaviour where a new array was created, prior to PHP 7.1.0.

Parameters

array

The input array.

values

The values to push onto the end of the array.

Return Values

Returns the new number of elements in the array.

Changelog

VersionDescription
7.3.0 This function can now be called with only one parameter. Formerly, at least two parameters have been required.

Examples

Example #1 array_push[] example

The above example will output:

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

See Also

  • array_pop[] - Pop the element off the end of array
  • array_shift[] - Shift an element off the beginning of array
  • array_unshift[] - Prepend one or more elements to the beginning of an array

Rodrigo de Aquino

10 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

14 years ago

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.

mrgreen dot webpost at gmail dot com

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

raat1979 at gmail dot com

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


Outputs:
Taken array;Array
[
    [foo] => bar
    [bar] => foo
]

push 1 returns 3
------------------------------------

push 2 returns 4
------------------------------------

add 1 returns 0

------------------------------------

add 2 returns 1

willdemaine at gmail dot com

14 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:



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

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



The above will output this:
Array [
  [0] => a
  [1] => b
  [2] => c
  [3] => Array [
     [0] => d
     [1] => e
     [2] => f
  ]
]

egingell at sisna dot com

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


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

asma dot gi dot 14 at gmail dot com

10 months ago

only variables could be passed by reference:
$arr = [1,2,3];
array_push[['a','b'],$arr] ; // error
array_push[$arr,[1,2,3]] ; // correct

David Spector

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

P.A.Semi

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

Carlos Alberto B. Carucce

3 years ago

This is how I add all the elements from one array to another:

gfuente at garrahan dot gov dot ar

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

helpmepro1 at gmail dot com

13 years ago

elegant php array combinations algorithm

aaron dot hawley at uvm dot edu

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

flobee

8 years ago

Be warned using $array "+=" array[1,2,3] or union operations [//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
]

Phil Davies

17 years ago

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

andrew at cgipro dot com

17 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

bk at quicknet dot nl

17 years ago

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

steve at webthoughts d\ot ca

16 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

Yields:

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

David Spector

1 year ago

A common operation when pushing a value onto a stack is to address the value at the top of the stack.

This can be done easily using the 'end' function:



Note: See the 'end' function for details about its side effect on the seldom used internal array pointer.

siqueiramoises14 at gmail dot com

2 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:



P.S: the array_key_last function it's for PHP >= 7.3.0 see more here //www.php.net/manual/en/function.array-key-last.php

wesleys at opperschaap dot net

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

Chủ Đề