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

前端 未结 19 2230
我寻月下人不归
我寻月下人不归 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:23

    When you do

    $array_x = $array_y;
    

    PHP copies the array, so I'm not sure how you would have gotten burned. For your case,

    global $foo;
    $foo = $obj->bar;
    

    should work fine.

    In order to get burned, I would think you'd either have to have been using references or expecting objects inside the arrays to be cloned.

    0 讨论(0)
  • 2020-12-07 07:24

    Creates a copy of the ArrayObject

    <?php
    // Array of available fruits
    $fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
    
    $fruitsArrayObject = new ArrayObject($fruits);
    $fruitsArrayObject['pears'] = 4;
    
    // create a copy of the array
    $copy = $fruitsArrayObject->getArrayCopy();
    print_r($copy);
    
    ?>
    

    from https://www.php.net/manual/en/arrayobject.getarraycopy.php

    0 讨论(0)
  • 2020-12-07 07:25

    This is the way I am copying my arrays in Php:

    function equal_array($arr){
      $ArrayObject = new ArrayObject($arr);
      return $ArrayObject->getArrayCopy();  
    }
    
    $test = array("aa","bb",3);
    $test2 = equal_array($test);
    print_r($test2);
    

    This outputs:

    Array
    (
    [0] => aa
    [1] => bb
    [2] => 3
    )
    
    0 讨论(0)
  • 2020-12-07 07:28

    If you have only basic types in your array you can do this:

    $copy = json_decode( json_encode($array), true);
    

    You won't need to update the references manually
    I know it won't work for everyone, but it worked for me

    0 讨论(0)
  • array_merge() is a function in which you can copy one array to another in PHP.

    0 讨论(0)
  • 2020-12-07 07:33

    I like array_replace (or array_replace_recursive).

    $cloned = array_replace([], $YOUR_ARRAY);

    It works like Object.assign from JavaScript.

    $original = [ 'foo' => 'bar', 'fiz' => 'baz' ];
    
    $cloned = array_replace([], $original);
    $clonedWithReassignment = array_replace([], $original, ['foo' => 'changed']);
    $clonedWithNewValues = array_replace([], $original, ['add' => 'new']);
    
    $original['new'] = 'val';
    

    will result in

    // original: 
    {"foo":"bar","fiz":"baz","new":"val"}
    // cloned:   
    {"foo":"bar","fiz":"baz"}
    // cloned with reassignment:
    {"foo":"changed","fiz":"baz"}
    // cloned with new values:
    {"foo":"bar","fiz":"baz","add":"new"}
    
    0 讨论(0)
提交回复
热议问题