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

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

提交回复
热议问题