Last active
November 27, 2016 13:26
-
-
Save sergeliatko/454959e76eec62e84e58c25fc9f40917 to your computer and use it in GitHub Desktop.
Parses arguments considering multi-dimensional arrays and objects
This file contains hidden or 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 | |
if( ! function_exists('wp_parse_args_recursive') ) { | |
/** | |
* Parses arguments considering multi-dimensional arrays and objects. | |
* | |
* @param mixed $args | |
* @param mixed $default | |
* @param bool $preserve_integer_keys | |
* | |
* @return mixed | |
*/ | |
function wp_parse_args_recursive( $args, $default, $preserve_integer_keys = false ) { | |
if ( ! is_array( $default ) && ! is_object( $default ) ) { | |
return wp_parse_args( $args, $default ); | |
} | |
$is_object = ( is_object( $args ) || is_object( $default ) ); | |
$output = array(); | |
foreach ( array( $default, $args ) as $elements ) { | |
foreach ( (array) $elements as $key => $element ) { | |
if ( is_integer( $key ) && ! $preserve_integer_keys ) { | |
$output[] = $element; | |
} elseif ( | |
isset( $output[ $key ] ) && | |
( is_array( $output[ $key ] ) || is_object( $output[ $key ] ) ) && | |
( is_array( $element ) || is_object( $element ) ) | |
) { | |
$output[ $key ] = wp_parse_args_recursive( | |
$element, | |
$output[ $key ], | |
$preserve_integer_keys | |
); | |
} else { | |
$output[ $key ] = $element; | |
} | |
} | |
} | |
return $is_object ? (object) $output : $output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment