This function gets the desired result. Specific types are assumed to be coherent with default types, so consistency checking is not performed. The function iterates over a specific configuration array and checks the corresponding default value 1 : if it is scalar, replace the default value; if it is an enumerated array 2, it combines unique values; otherwise, the function calls itself with the current values as arguments.
function fillConfig( $default, $specific ) { foreach( $specific as $key=> $val ) { if( isset( $default[$key] ) ) { if( ! is_array( $default[$key] ) ) { $default[$key] = $val; } elseif( array_keys($default[$key]) === range(0, count($default[$key]) - 1) ) { $default[$key] = array_unique( array_merge( $default[$key], $val ) ); } else { $default[$key] = fillConfig( $default[$key], $val ); } } else {
The function call is as follows:
$result = fillConfig( $defaultConfigs, $specificConfigs );
$result applied to your sample arrays is as follows:
Array ( [scalar1] => A [scalar2] => Apple [array_scalar] => Array ( [0] => 3 [1] => 4 [2] => 5 ) [array_associative] => Array ( [scalar] => 1 [array_scalar] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [array_associative] => Array ( ) ) )
With this array of steam:
$defaultConfigs = [ 'scalar1' => 1, 'scalar2' => "Apple", 'array_scalar' => [3,4,5], 'array_associative' => [ 'scalar' => 1, 'array_scalar' => [1,2,3], 'array_associative' => [ ] ], ]; $specificConfigs = [ 'scalar1' => "A", 'array_scalar' => [3,4,5], 'array_associative' => [ 'scalar' => B, 'array_scalar' => [3,4,5], 'array_associative' => [ ] ], ];
$result :
Array ( [scalar1] => A [scalar2] => Apple [array_scalar] => Array ( [0] => 3 [1] => 4 [2] => 5 ) [array_associative] => Array ( [scalar] => B [array_scalar] => Array ( [0] => 1 [1] => 2 [2] => 3 [4] => 4 [5] => 5 ) [array_associative] => Array ( ) ) )
Notes:
1 Yes, this is a little incoherent: I felt that it was better to iterate over a specific array (non-existing elements remain untouched), but they perform a check of the default value, that is, a breakpoint.
2 Enum / associative array validation is based on this answer .