6

I need a solution for array_replace_recursive, because my php-version isn't high enough. I want to use this code:

$_GET = array_replace_recursive($_GET, array("__amp__"=>"&"));

easy, isn't it?

SilentGhost
322k67 gold badges312 silver badges294 bronze badges
asked May 20, 2010 at 13:18

2 Answers 2

5

On the PHP docs page for array_replace_recursive, someone posted the following source code to use in place of it:

<?php
if (!function_exists('array_replace_recursive'))
{
 function array_replace_recursive($array, $array1)
 {
 function recurse($array, $array1)
 {
 foreach ($array1 as $key => $value)
 {
 // create new key in $array, if it is empty or not an array
 if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key])))
 {
 $array[$key] = array();
 }
 // overwrite the value in the base array
 if (is_array($value))
 {
 $value = recurse($array[$key], $value);
 }
 $array[$key] = $value;
 }
 return $array;
 }
 // handle the arguments, merge one by one
 $args = func_get_args();
 $array = $args[0];
 if (!is_array($array))
 {
 return $array;
 }
 for ($i = 1; $i < count($args); $i++)
 {
 if (is_array($args[$i]))
 {
 $array = recurse($array, $args[$i]);
 }
 }
 return $array;
 }
}
?>
answered May 20, 2010 at 13:20

1 Comment

When using the function more than once, I get: Fatal error: Cannot redeclare recurse()
1

The code above by @Justin is ok, save for 2 things:

  1. Function is not readily available at start of php execution be cause it is wrapped in if(). PHP docu says

    When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

  2. Most importantly; calling the function twice results in fatal error. PHP docu says

    All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

So I just moved the recurse function outside array_replace_recursive function and it worked well. I also removed the if() condition and renamed it to array_replace_recursive_b4php53 for fear of future upgradings

Toby Speight
31.7k57 gold badges80 silver badges115 bronze badges
answered Mar 12, 2015 at 9:38

1 Comment

This should be a comment on Justin's answer (because space is limited in a comment, you could post the full message in a link). Flagged as this is not an answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.