Is there a function to make a copy of a PHP array to another?

前端 未结 19 2227
我寻月下人不归
我寻月下人不归 2020-12-07 06:44

Is there a function to make a copy of a PHP array to another?

I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an obj

相关标签:
19条回答
  • 2020-12-07 07:11

    simple and makes deep copy breaking all links

    $new=unserialize(serialize($old));
    
    0 讨论(0)
  • 2020-12-07 07:11
    private function cloneObject($mixed)
    {
        switch (true) {
            case is_object($mixed):
                return clone $mixed;
            case is_array($mixed):
                return array_map(array($this, __FUNCTION__), $mixed);
            default:
                return $mixed;
        }
    }
    
    0 讨论(0)
  • 2020-12-07 07:14

    Define this:

    $copy = create_function('$a', 'return $a;');
    

    Copy $_ARRAY to $_ARRAY2 :

    $_ARRAY2 = array_map($copy, $_ARRAY);
    
    0 讨论(0)
  • 2020-12-07 07:16

    If you have an array that contains objects, you need to make a copy of that array without touching its internal pointer, and you need all the objects to be cloned (so that you're not modifying the originals when you make changes to the copied array), use this.

    The trick to not touching the array's internal pointer is to make sure you're working with a copy of the array, and not the original array (or a reference to it), so using a function parameter will get the job done (thus, this is a function that takes in an array).

    Note that you will still need to implement __clone() on your objects if you'd like their properties to also be cloned.

    This function works for any type of array (including mixed type).

    function array_clone($array) {
        return array_map(function($element) {
            return ((is_array($element))
                ? array_clone($element)
                : ((is_object($element))
                    ? clone $element
                    : $element
                )
            );
        }, $array);
    }
    
    0 讨论(0)
  • 2020-12-07 07:18

    I know this as long time ago, but this worked for me..

    $copied_array = array_slice($original_array,0,count($original_array));
    
    0 讨论(0)
  • 2020-12-07 07:18

    $arr_one_copy = array_combine(array_keys($arr_one), $arr_one);

    Just to post one more solution ;)

    0 讨论(0)
提交回复
热议问题