14

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?

3

6 Answers 6

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Seems array_merge overwrites, where + is the same function but does not overwrite. Got it, thanks :)
You can also use += operator like so $post_values += ['x_version' => '3.1', 'x_zip' => 98004];
7

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!)

Comments

3

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

1 Comment

array_push() will not preserve associative keys on its own. This answer is either misleading or needs to be better explained about caveats.
1

You can try using the following function: array_merge

1 Comment

This doc-link answer could have been posted as a comment under the question because it only endeavors to redirect traffic.
1

You can also use the spread operator:

$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
)

6 Comments

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 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.
Hi @mickmackusa, here's a snippet of what I ment: onlinephp.io?s=lZBBa8JAEIXPDeQ_TCVgQmyM6a1qexJ6aKkgPYnIYlazpe6E… I might not have been clear enough how I meant that, so I removed the hint to performance in my post...
Please review this adjusted benchmarking script where I've isolated the operations into separate functions. 3v4l.org/J78dk
Sorry for the late reply, my original claim was not to use the spread operator inside the loop. Instead I prepare an array so that the spread operator can be used only once in combination with array_merge, after the loop.
I suppose my ultimate point is that there isn't a clear advantage in using [...one, ...$two] versus the more concise union operator [$one + $two].
|
0

A simple method to avoid complications and mixups, simply use +=

Example:

$data = ["one" => 1];
$data += [ "two" => 2 ];
$data += [ "three" => 3, "four" => 4];
print_r($data);

Result: Array ( [one] => 1 [two] => 2 [three] => 3 [four] => 4 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.