459

Take a look at this code:

$GET = array();    
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */

I'm looking for something like this so that:

print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */

Is there a function to do this? (because array_push won't work this way)

Shady Mohamed Sherif
  • 15,003
  • 4
  • 45
  • 54
Gal
  • 23,122
  • 32
  • 97
  • 118

21 Answers21

962

Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.

You'll have to use

$arrayname[indexname] = $value;
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • How to add multiple keys and values to an array? for example I have [indexname1] = $value1 and [indexname2] = $value2, and I want to add them to $arrayname – King Goeks Oct 30 '13 at 07:59
  • 13
    @KingGoeks `$arrayname = array('indexname1' => $value1, 'indexname2' => $value2);` would set them as the only items in `$arrayname`. If you already have `$arrayname` set and want to keep its values, try `$arrayname += $anotherarray`. Keep in mind any existing keys in the first array would be overwritten by the second. – Charlie Schliesser Dec 17 '13 at 23:09
  • 2
    "Keep in mind any existing keys in the first array would be overwritten by the second" that is not true, the first array has priority. if you do `$a = array("name" => "John"); $a += array("name" => "Tom");`then `$a["name"]` will be "John" – santiago arizti Jan 31 '18 at 16:16
  • it is the faster of the two: array_push vs array[]. Array[] is about 2x as fast if i remember correctly... – jasonflaherty Nov 20 '19 at 18:18
  • this is very fine and possibly the best for named-key arrays; only ensure that the key-name (the named index) does not clash with an already existing one. also ensure that the parent array exists first before you start 'pushing' your items into it. – Ajowi Apr 24 '20 at 05:40
  • Warning: `$a['123'] = 456;` - string '123' is converted to integer key 123. – bancer Jul 02 '20 at 12:56
  • I have been coding professionally in php for more than 2 years..... I am ashamed that I actually had to look for this and didnt immediately click in my brain. – Mash tan Jul 14 '22 at 11:02
102

Pushing a value into an array automatically creates a numeric key for it.

When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.

// no key
array_push($array, $value);
// same as:
$array[] = $value;

// key already known
$array[$key] = $value;
deceze
  • 510,633
  • 85
  • 743
  • 889
88

You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:

<?php

$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;

print_r($arr3);

// prints:
// array(
//   'foo' => 'bar',
//   'baz' => 'bof',
// );

So you could do $_GET += array('one' => 1);.

There's more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.

Charlie Schliesser
  • 7,851
  • 4
  • 46
  • 76
  • 6
    The basic difference between `array_merge()` and `+` operator is when the 2 arrays contain values on the same key `+` operator ignores the value from second array (does not override), also it does not renumber/reindex the numeric keys... – jave.web Feb 16 '17 at 21:35
64

I wonder why the simplest method hasn't been posted yet:

$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
AlexioVay
  • 4,338
  • 2
  • 31
  • 49
  • 2
    it is not exactly the same, in array_merge, the array on the right wins on key conflict, in " += " the array on the left wins – santiago arizti Jan 31 '18 at 16:18
  • @santiagoarizti What do you mean by "wins"? – AlexioVay Aug 27 '19 at 09:13
  • 2
    if two arrays have both the same key, `array_merge` and *array union* (`+=`) behave in the opposite way i.e. array_merge will respect the value from the second array and array union will respect the value from the first array. – santiago arizti Aug 28 '19 at 15:49
  • 3
    Legend!! Just `$arr += [$key => $value];` did it perfectly fine for me, thanks! –  Feb 16 '22 at 16:27
25

I would like to add my answer to the table and here it is :

//connect to db ...etc
$result_product = /*your mysql query here*/ 
$array_product = array(); 
$i = 0;

foreach ($result_product as $row_product)
{
    $array_product [$i]["id"]= $row_product->id;
    $array_product [$i]["name"]= $row_product->name;
    $i++;
}

//you can encode the array to json if you want to send it to an ajax call
$json_product =  json_encode($array_product);
echo($json_product);

hope that this will help somebody

Nassim
  • 2,879
  • 2
  • 37
  • 39
21

Exactly what Pekka said...

Alternatively, you can probably use array_merge like this if you wanted:

array_merge($_GET, array($rule[0] => $rule[1]));

But I'd prefer Pekka's method probably as it is much simpler.

jeffff
  • 1,309
  • 1
  • 7
  • 23
11

2023

A lot of answers. Some helpful, others good but awkward. Since you don't need complicated and expensive arithmetic operations, loops etc. for a simple operation like adding an element to an array, here is my collection of One-Liner-Add-To-Array-Functions.

$array = ['a' => 123, 'b' => 456]; // init Array

$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.

print_r($array);
// Output:
/* 
Array
(
    [a] => 123
    [b] => 456
    [c] => 789
    [d] => 012
    [e] => 345
    [f] => 678
)
*/

In 99,99% i use version 1. ($array['c'] = 789;). But i like version 4. That is the version with the splat operator (https://www.php.net/manual/en/migration56.new-features.php).

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
9

I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.

I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.

Pretty easy & simple really


// Get All Settings
$settings=getGlobalSettings();


// Apply User Theme Choice
$theme_choice = $settings['theme'];

.. etc etc etc ....




function getGlobalSettings(){

    $dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
    mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
    $MySQL = "SELECT * FROM systemSettings";
    $result = mysqli_query($dbc, $MySQL);
    while($row = mysqli_fetch_array($result)) 
        {
        $settings[$row['item']] = $row['value'];   // NO NEED FOR PUSH
        }
    mysqli_close($dbc);
return $settings;
}


So like the other posts explain... In php there is no need to "PUSH" an array when you are using

Key => Value

AND... There is no need to define the array first either.

$array=array();

Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.

I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!

Cory Cullers
  • 139
  • 1
  • 2
9

A bit late but if you don't mind a nested array you could take this approach:

$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));

To clarify, if you output json_encode($main_array) that will look like [{"Key":"10"}]

theBigBadBacon
  • 129
  • 1
  • 5
8

This is the solution that may useful for u

Class Form {
# Declare the input as property
private $Input = [];

# Then push the array to it
public function addTextField($class,$id){
    $this->Input ['type'][] = 'text';
    $this->Input ['class'][] = $class;
    $this->Input ['id'][] = $id;
}

}

$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');

When you dump it. The result like this

array (size=3)
  'type' => 
    array (size=3)
      0 => string 'text' (length=4)
      1 => string 'text' (length=4)
      2 => string 'text' (length=4)
  'class' => 
    array (size=3)
      0 => string 'myclass1' (length=8)
      1 => string 'myclass2' (length=8)
      2 => string 'myclass3' (length=8)
  'id' => 
    array (size=3)
      0 => string 'myid1' (length=5)
      1 => string 'myid2' (length=5)
      2 => string 'myid3' (length=5)
Faris Rayhan
  • 4,500
  • 1
  • 22
  • 19
4

A bit weird, but this worked for me

    $array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
    $array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
    $array3 = array();

    $count = count($array1);

    for($x = 0; $x < $count; $x++){
       $array3[$array1[$x].$x] = $array2[$x];
    }

    foreach($array3 as $key => $value){
        $output_key = substr($key, 0, -1);
        $output_value = $value;
        echo $output_key.": ".$output_value."<br>";
    }
3
 $arr = array("key1"=>"value1", "key2"=>"value");
    print_r($arr);

// prints array['key1'=>"value1", 'key2'=>"value2"]

sneha
  • 147
  • 3
3

The simple way:

$GET = array();    
$key = 'one=1';
parse_str($key, $GET);

http://php.net/manual/de/function.parse-str.php

eSlider
  • 181
  • 1
  • 4
3

Example array_merge()....

$array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result);

Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)

illeas
  • 300
  • 3
  • 18
3

I wrote a simple function:

function push(&$arr,$new) {
    $arr = array_merge($arr,$new);
}

so that I can "upsert" new element easily:

push($my_array, ['a'=>1,'b'=>2])
Elect2
  • 1,349
  • 2
  • 12
  • 22
2
array_push($arr, ['key1' => $value1, 'key2' => value2]);

This works just fine. creates the the key with its value in the array

Mesh Manuel
  • 104
  • 1
  • 8
2

hi i had same problem i find this solution you should use two arrays then combine them both

 <?php

$fname=array("Peter","Ben","Joe");

$age=array("35","37","43");

$c=array_combine($fname,$age);

print_r($c);

?>

reference : w3schools

fantome195
  • 31
  • 2
2

For add to first position with key and value

$newAarray = [newIndexname => newIndexValue] ;

$yourArray = $newAarray + $yourArray ;
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
1

There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.

$intial_content = array();

if (true) {
 $intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}
Deepak Rajpal
  • 811
  • 1
  • 8
  • 11
0
array_push($GET, $GET['one']=1);

It works for me.

Anbuselvan Rocky
  • 606
  • 6
  • 22
aaa
  • 25
  • 1
  • 1
    This executes `$GET['one']=1`, then uses the return value of that statement (=1, the rvalue), and then executes `array_push($GET, 1)`. Result = [0]->1, [one]->1 – KekuSemau Jul 08 '19 at 06:12
-3

I usually do this:

$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
marcnyc
  • 585
  • 1
  • 4
  • 17