Thursday, May 24, 2012

When to use array_merge and union operator (+) in PHP?


array_merge

Use array_merge when you want to merge indexed arrays without keys:


Output:


Array Union Operator (+)


Use the union operator when you want to extend an array or override certain key values. A good use case for this is overriding/extending a default settings array with a user defined array (similar to how you would use $.extend while writing a jQuery plugin):


Output:



References


1 comment:

Anonymous said...

I find this confusing:

$default_settings = array('page'=>3, 'per_page'=>100);
$user_override = array('per_page'=>50, 'format'=>'json');
$overriden_setting = $user_override + $default_settings;

I would rather write either:

$default_settings = array('page'=>3, 'per_page'=>100);
$user_override = array('per_page'=>50, 'format'=>'json');
$overridden_settings = array_merge($default_settings, $user_override);

or:

$minimal_settings = array('page'=>3, 'per_page'=>100);
$user_provided = array('per_page'=>50, 'format'=>'json');
$completed_settings = $user_provided + $minimal_settings;