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?
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.
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" );
To extend an existing array in JavaScript, use the Array. concat() method.
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', // );
You can also use the +
operator:
$combined = $_SESSION['results'] + $_POST;
array_merge() is the function you're after.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With