Adding multiple values to an associative array in PHP in one call

ViviDVasT picture ViviDVasT · Oct 30, 2011 · Viewed 21.2k times · Source

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?

Answer

Deleted picture Deleted · Oct 30, 2011

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.