Background
I was using array_replace_recursive() to merge default option values and user-defined parameter values. However, it is supported in PHP 5.3 or above. Then some of my users reported that my plugin does not work with a fatal error.
So I wrote up an alternative for it. One limitation though is that it only accepts two parameters unlike the PHP’s array_replace_recursive() which supports more than two.
Anyhow this is the code and hope it helps somebody else who gets a similar issue.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function uniteArraysRecursive( $arrPrecedence, $arrDefault ) { if ( is_null( $arrPrecedence ) ) $arrPrecedence = array(); if ( ! is_array( $arrDefault ) || ! is_array( $arrPrecedence ) ) return $arrPrecedence; foreach( $arrDefault as $strKey => $v ) { // If the precedence does not have the key, assign the default's value. if ( ! array_key_exists( $strKey, $arrPrecedence ) || is_null( $arrPrecedence[ $strKey ] ) ) $arrPrecedence[ $strKey ] = $v; else { // if the both are arrays, do the recursive process. if ( is_array( $arrPrecedence[ $strKey ] ) && is_array( $v ) ) $arrPrecedence[ $strKey ] = $this->uniteArraysRecursive( $arrPrecedence[ $strKey ], $v ); } } return $arrPrecedence; } |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
$arr1 = array( 'a' => 'apple', 'b' => 'bb', 'c' => 'cc', 'd' => 'dddd', 'e' => array( 'a_a' => null, 'b_b' => 'b_bb', 'c_c' => 'c_cc', 'bar' => 'bar', 'f' => array( 'f_a' => 'fa', 'f_b' => 'fb', 'f_c' => 'fc', ) ), ); $arr2 = array( 'a' => 'aa', 'b' => 'bb', 'd' => 'dang!', 'e' => array( 'a_a' => 'a_aa', 'b_b' => 'b_bb', 'c_c' => 'c_cc', 'g' => array( 'g_a' => 'ga', 'g_b' => 'gb', 'g_c' => 'gc', ) ), ); $array = uniteArraysRecursive( $arr1, $arr2 ); echo '<pre>' . print_r( $array, true ). '</php>'; |
Result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Array ( [a] => apple [b] => bb [c] => cc [d] => dddd [e] => Array ( [a_a] => [b_b] => b_bb [c_c] => c_cc [bar] => bar [f] => Array ( [f_a] => fa [f_b] => fb [f_c] => fc ) [g] => Array ( [g_a] => fa [g_b] => fb [g_c] => fc ) ) ) |
Just be aware the parameters to uniteArraysRecursive() are the opposite way round to PHP’s array_replace_recursive()