Combine array "Defaults" with array "Input"? PHP What function?

Suppose you provide information to a user.

Array 1 

But not everything is required. That way you have the default values.

 Array 2 

Does PHP have a function that will overwrite all values โ€‹โ€‹of an Array 2 based array if they are supplied in Array 1 and not empty?

+9
source share
5 answers

I think you are looking for array_replace_recursive , especially for the case when your "defaults" can be an associative array with a depth of more than one level.

$finalArray = array_replace_recursive(array $defaults, array $inputOptions)

Here is an example that takes an optional array of options for a function and does some processing based on the result of the opts and defaults options that you specify:

 function do_something() { $args = func_get_args(); $opts = $args[0] ? $args[0] : array(); $defaults = array( "second_level" => array( "key1" => "val1", "key2" => "val2" ), "key1" => "val1", "key2" => "val2", "key3" => "val3" ); $params = array_replace_recursive($defaults, $opts); // do something with these merged parameters } 

Php.net help document here here

+19
source
 $defaults = array( 'some_key_1'=>'default_value_1', 'some_key_2'=>'default_value_2', ); $inputs = array_merge($defaults, $inputs) 

Note that if the $ input array contains keys that are not in the $ defaults array, they will be added to the result.

+2
source

array_merge () is exactly what you are looking for.

+1
source

If you just want to keep the expected options and abandon the rest, you can use a combination of array_merge and array_intersect_key .

 <?php function foo($options) { $defaults = [ 'a' => 1, 'b' => null, ]; $mergedParams = array_merge( $defaults, array_intersect_key($options, $defaults) ); return $mergedParams; } var_dump(foo([ 'a' => 'keep me', 'c' => 'discard me' ])); // => output // // array(2) { // ["a"]=> // string(7) "keep me" // ["b"]=> // NULL // } 

If you want to save the extra key, then array_merge($defaults, $options) will work fine.

+1
source

You can just do something like

 foreach($array1 as $key=>$value) $array2[$key]=$value; 
0
source

All Articles