Home » Php » php – Adding array to existing array without invoking a new key

php – Adding array to existing array without invoking a new key

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

You can also use the + operator:

$combined = $_SESSION['results'] + $_POST;

Answer:

array_merge() is the function you’re after.

Answer:

array_merge() is your answer see http://php.net/manual/en/function.array-merge.php

Answer:

You have to use array_merge(), look at this: array_merge()