Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: array_replace_recursive alternative

Tags:

arrays

php

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?

like image 420
Glubber Avatar asked May 20 '10 13:05

Glubber


2 Answers

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;
  }
}
?>
like image 95
Justin Ethier Avatar answered Oct 31 '22 21:10

Justin Ethier


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

like image 21
mikewasmike Avatar answered Oct 31 '22 21:10

mikewasmike