PHP - replace values of array with another array

后端 未结 5 1309
别那么骄傲
别那么骄傲 2021-01-19 14:56

Is there a way i can replace the values of one array with the values of another which has identical keys?

$arr1 = Array
        (
            [key1] => va         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 15:30

    Editing Notes: This answer previously suggested using array_combine as a way of doing this. However, as several people have pointed out, that's not the correct way of solving this problem. This answer has been edited to be more relevant to actually solving the problem.


    To replace the values of one array with the values of another array you can use the PHP array_replace method. This assumes associative arrays with identical keys.

    The PHP documentation explains array_replace like this:

    array_replace() replaces the values of array1 with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.


    Also, this post: https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/ includes a handy graphic which helps to explain the difference between array_merge, array_replace, and the array union operator (+). Give the post the read if you desire, I've included the image below for reference:

提交回复
热议问题