Created
October 20, 2015 10:46
-
-
Save ckchaudhary/f0f9011d2b30665c1892 to your computer and use it in GitHub Desktop.
php merge and override arrays recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Merge given arrays, overriding $defaults array with values from $args array recursively. | |
* | |
* @author ckchaudahry | |
* | |
* @param $args array | |
* @param $defaults array | |
* | |
* @return array | |
*/ | |
function wdw_merge_array_recursively( $args, $defaults ) { | |
$merged = array(); | |
//first all values from args | |
foreach( $args as $arg_key=>$arg_val ){ | |
if( is_array( $arg_val ) && array_key_exists( $arg_key, $defaults ) ){ | |
$merged[$arg_key] = wdw_merge_array_recursively( $arg_val, $defaults[$arg_key] ); | |
} else { | |
if( empty( $arg_val ) && isset( $defaults[$arg_key] ) ){ | |
$merged[$arg_key] = $defaults[$arg_key]; | |
} else { | |
$merged[$arg_key] = $arg_val; | |
} | |
} | |
} | |
//then all values from defaults | |
foreach ( $defaults as $def_key=>$def_val ) { | |
if ( !array_key_exists( $def_key, $merged ) ) { | |
$merged[$def_key] = $def_val; | |
} | |
} | |
return $merged; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment