Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding array to existing array without invoking a new key

Tags:

arrays

php

I'm building a 3 page submission form, and I'd quite like all of the $_POST results to be stored in a single session variable.

So page 1 starts by setting up the array and adding the first lot of post data:

$_SESSION['results'] = array();
$_SESSION['results'] = $_POST // first lot of post data

This works great and returns an array like:

Array
(
  [name] => bob
  [address] => 1 foobar way
  [age] => 100
)

So when I get the resuts from page 2, I want to simply append them to the existing array without invoking a new array+key

array_push($_SESSION['results'], $_POST); //second lot of post data

To get something like this:

Array
(
  [name] => bob
  [address] => 1 foobar way
  [age] => 100
  [job] => rubbish php dev
  [salary] => 1000
)

But instead I get:

Array
(
  [name] => bob
  [address] => 1 foobar way
  [age] => 100
  [0] => Array
    (
      [job] => rubbish php dev
      [salary] => 1000
    )
)

Even more annoying is that I'm sure I had this working properly before I tweaked the code. What am I doing wrong?

like image 235
James Avatar asked Mar 20 '13 13:03

James


People also ask

How do you add an array to another array?

To append one array to another, call the concat() method on the first array, passing it the second array as a parameter, e.g. const arr3 = arr1. concat(arr2) . The concat method will merge the two arrays and will return a new array.

How can I add one array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );

How do you extend an array in JavaScript?

To extend an existing array in JavaScript, use the Array. concat() method.

How do you push a key into an array?

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', // );


2 Answers

You can also use the + operator:

$combined = $_SESSION['results'] + $_POST;
like image 180
jeroen Avatar answered Oct 25 '22 01:10

jeroen


array_merge() is the function you're after.

like image 38
juco Avatar answered Oct 25 '22 02:10

juco