Far all the developers, WordPress has created a nifty function called wp_parse_args which is quite useful when merging two sets of data arrays and is similar to native PHP function array_merge. The only lack of feature is that it is not recursive which makes it unable to handle and merge multidimensional arrays properly. Luckily, here is our solution.
What wp_parse_args function does?
It is very similar to the native PHP array_merge() function. From our experience so far, we found out that major usage of wp_parse_args function is when you need to pass a set of arguments as an array and make sure that default arguments which further code requires are populated. Here’s a basic example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //An array of data with dynamically set arguments $args = array( 'top' => 4, 'right' => 3 ); //Default arguments $defaults = array( 'top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0 ); //Merge arguments and make sure that default data is set even if not passed explicitly in $args $data = wp_parse_args( $args, $defaults ); |
So far, so good. But, what if we have a two multidimensional PHP arrays we need to merge? Unfortunately, wp_parse_args function is useless in such case.
Introducing meks_wp_parse_args function (to merge multidimensional PHP arrays)
Whilst we needed to merge multidimensional arrays in some cases we have created our own function as a replacement for wp_parse_args. It will iterate through entire array and call itself recursively whenever it finds another array passed as an argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /* Similar to wp_parse_args() just a bit extended to work with multidimensional arrays :) */ function meks_wp_parse_args( &$a, $b ) { $a = (array) $a; $b = (array) $b; $result = $b; foreach ( $a as $k => &$v ) { if ( is_array( $v ) && isset( $result[ $k ] ) ) { $result[ $k ] = meks_wp_parse_args( $v, $result[ $k ] ); } else { $result[ $k ] = $v; } } return $result; } |
Usage example
Here is a real case scenario in which you will rather use our function instead of wp_parse_args.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //An array of data with dynamically set arguments (which are multidimensional in this case) $args = array( 'top' => 4, 'right' => 3, 'display_on' => array( 'category' => false ) ); //Default arguments (which are multidimensional in this case) $defaults = array( 'top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0, 'display_on' => array( 'single' => true, 'category' => true, 'page' => true ) ); //Magic $data = meks_wp_parse_args( $args, $defaults ); |
That’s it, just copy entire meks_wp_parse_args function code inside your theme functions.php or a plugin and you can start using it. Feel free to try and give us some feedback!