Replace the values of the first array ($a1) with the values of the second array ($a2):
<?php$a1=array("red","green");$a2=array("blue","yellow");print_r(array_replace($a1,$a2));?>The array_replace() function replaces the values of the first array with the values of the following array.
Tip: You can pass an array, or multiple arrays, to the function.
If a key exists in the first array array1 and also exists in the second array array2, the value in the first array array1 will be replaced by the value in the second array array2. If a key only exists in the first array array1, it will remain unchanged. (See Example 1 below for details)
If a key exists in the second array, array2, but not in the first array, array1, the element will be created in the first array, array1. (See Example 2 below for details)
If multiple replacement arrays are passed, they will be processed in order, and the values of subsequent arrays will overwrite the values of previous arrays. (See Example 3 below for details)
Tip: Use array_replace_recursive() to recursively replace the values of the first array with the values of subsequent arrays.
array_replace( array1,array2,array3... )
parameter | describe |
---|---|
array1 | Required. Specify an array. |
array2 | Optional. Specifies an array to replace the value of array1 . |
array3,... | Optional. Specify multiple arrays to replace the values of array1 and array2, .... The values in the following array will overwrite the values in the previous array. |
Return value: | Returns the replaced array, or NULL if an error occurs. |
---|---|
PHP version: | 5.3.0+ |
If a key exists in the first array array1 and also exists in the second array array2, the value in the first array array1 will be replaced by the value in the second array array2. If a key only exists in the first array array1, it will remain unchanged.
<?php$a1=array("a"=>"red","b"=>"green");$a2=array("a"=>"orange","burgundy");print_r(array_replace( $a1,$a2));?>If a key exists in the second array, array2, but not in the first array, array1, the element will be created in the first array, array1.
<?php$a1=array("a"=>"red","green");$a2=array("a"=>"orange","b"=>"burgundy");print_r(array_replace( $a1,$a2));?>Using three arrays - the last array ($a3) will overwrite the previous arrays ($a1 and $a2):
<?php$a1=array("red","green");$a2=array("blue","yellow");$a3=array("orange","burgundy");print_r(array_replace($ a1,$a2,$a3));?>Use numeric keys - if a key exists in the second array array2, but not in the first array array1, the element will be created in the first array array1:
<?php$a1=array("red","green","blue","yellow");$a2=array(0=>"orange",3=>"burgundy");print_r(array_replace($ a1,$a2));?>