How To Write Function array_replace_recursive To Support Old PHP Version

How to write a function array_replace_recursive to support old PHP version like PHP 5.2.

The following codes will array_replace_recursive function for PHP 5.2 or older

<?php
if (!function_exists('array_replace_recursive')){
    function array_replace_recursive($base, $replacements){
        foreach (array_slice(func_get_args(), 1) as $replacements) {
            $bref_stack = array(&$base);
            $head_stack = array($replacements);
            do {
                end($bref_stack);
                $bref = &$bref_stack[key($bref_stack)];
                $head = array_pop($head_stack);
                unset($bref_stack[key($bref_stack)]);
                foreach (array_keys($head) as $key) {
                    if (isset($key, $bref) && is_array($bref[$key]) && is_array($head[$key])) {
                        $bref_stack[] = &$bref[$key];
                        $head_stack[] = $head[$key];
                    } else {
                        $bref[$key] = $head[$key];
                    }
                }
            } while(count($head_stack));
        }
        return $base; 
    }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments