12

I am trying instantiate an associative array and then in a second call, assign it various other value sets on one block-line. I would like to do this following the same form as in the instantiation:

"variable"  = > 'value';

My instantiation is:

$post_values = array(
    "x_login"           => "API_LOGIN_ID",
    "x_tran_key"        => "TRANSACTION_KEY",
);

I would like to add:

"x_version"         => "3.1",
"x_delim_data"      => "TRUE",
"x_delim_char"      => "|",
"x_relay_response"  => "FALSE",
"x_state"           => "WA",
"x_zip"             => "98004"

What are my options? Perhaps there's an array_push usage that I don't know about to add multiple values with more ease? Or am i stuck adding on value per call like:

$post_values['x_version']='3.1'; 
 ....
$post_values['x_zip']='98004';

Is there any other graceful way to do add multiple values to an associative array in one line?

ViviDVasT
  • 131
  • 1
  • 1
  • 6
  • see related answer [in one call] here :: @the bottom;; http://stackoverflow.com/questions/6123122/how-to-push-hash-into-array-of-hash-in-php – ek- Nov 21 '13 at 10:23
  • It is unclear how the new data is accessed. Is it an array? Are they accessible as a individual variables? Is `array_replace()` not suitable? What is the desired output if keys are shared between the two arrays? Robust [mcve]s are important. – mickmackusa May 16 '23 at 00:00
  • Possibly tangentially related: [PHP is there a way to add elements calling a function from inside of array](https://stackoverflow.com/q/35548170/2943403) and [Merge two arrays into one multi-dimensional array](https://stackoverflow.com/q/24443086/2943403) – mickmackusa May 16 '23 at 00:06

5 Answers5

9

Try this:

$post_values = array( 
    "x_login"           => "API_LOGIN_ID", 
    "x_tran_key"        => "TRANSACTION_KEY", 
); 

$array2 = array(
    "x_version"         => "3.1",  
    "x_delim_data"      => "TRUE",  
    "x_delim_char"      => "|",  
    "x_relay_response"  => "FALSE",  
    "x_state"           => "WA",  
    "x_zip"             => "98004"  
);

$result = $post_values + $array2;

Caution however: If the key already exists in $post_values it will not be overwritten.

Deleted
  • 4,804
  • 1
  • 22
  • 17
6

In order to keep things nice and clean and in this case, simple, you might be better off using array_merge( )

I personally declare any arrays at the top of my class file, in order to make them globally accessible, only because I tend to keep methods free of array declaration (OCD I guess!)

So for me I have an example that might help you, it's something that works for me when needed to add/merge two arrays together:

protected $array1 = array (
  'basic'   => '1',
  'example' => '2',
  'for'     => '3'  
);

protected $array2 = array(
  'merging'     => '4',
  'two'         => '5',
  'associative' => '6',
  'arrays'      => '7',
  'mate'        => '8'
);

Then within your class file, you can use these arrays or any created arrays and merge whenever you want:

public function ExampleOne() 
{
  $firstArray = $this->array1;
  print_r($firstArray);
  
  $secondArray = $this->array2;
  print_r($secondArray);

  $merged = array_merge($firstArray, $secondArray);
  print_r($merged);
}

Each print_r( ) will give you a print out in the console of the data/created array. This is so you can view for yourself that everything has been created correctly and each key has its associated value (check the PHP man pages for a definitive explanation of print_r( ) ).

So, the first array will/should showcase this:

Array
(
  [basic]   => 1
  [example] => 2
  [for]     => 3
)

The second array will/should showcase this:

Array
(
  [merging]     => 4
  [two]         => 5
  [associative] => 6
  [arrays]      => 7
  [mate]        => 8
)

And the array_merge( ) operation will create the final array, which will/should showcase this:

Array
(
  [basic]       => 1
  [example]     => 2
  [for]         => 3
  [merging]     => 4
  [two]         => 5
  [associative] => 6
  [arrays]      => 7
  [mate]        => 8
)

Of course, you don't always have to place/create your arrays at the top of the class file and when needed you can obviously create arrays within a single function if they are only needed/used within there - what I showcased here was just something I had done recently for a project at work (with the data in these arrays being example data of course!)

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Vin Chenzo
  • 81
  • 1
  • 5
2

array_push() will accept an array to be pushed.
But array_merge() may be more what you want.

Siguza
  • 21,155
  • 6
  • 52
  • 89
John Watson
  • 2,554
  • 1
  • 17
  • 13
  • 1
    `array_push()` will not preserve associative keys on its own. This answer is either misleading or needs to be better explained about caveats. – mickmackusa May 16 '23 at 00:02
1

You can try using the following function: array_merge

  • This doc-link answer could have been posted as a comment under the question because it only endeavors to redirect traffic. – mickmackusa May 16 '23 at 00:03
0

You can also use the spread operator which is faster if you have to merge the arrays in a loop:

$post_values = [ 
    "x_login"    => "aaa", 
    "x_tran_key" => "bbb", 
];

$dataToAdd = [
    "foo" => "abc",  
    "bar" => "def",  
];

$result = [
    ...$post_values,
    ...$dataToAdd
];

print_r($result);

Which results to:

Array
(
    [x_login] => aaa
    [x_tran_key] => bbb
    [foo] => abc
    [bar] => def
)
Matthias
  • 591
  • 5
  • 4
  • I am interested in seeing the benchmarking script and sample data that you used to prove that unpacking multiple arrays into an array "is faster". [Splatpacking versus array_values() to re-index an array with numeric keys](https://stackoverflow.com/q/57725811/2943403) seems to indicate that unpacking, just to re-pack is not a performant solution. I would be surprised if your snippet outperformed the `array union` operator. It would be helpful to compare your suggestion against all other similarly functioning techniques. – mickmackusa May 15 '23 at 23:57