PHP array_replace() Function

PHP array_replace Function


The array_replace() function replaces the values in an array with the values from other arrays.

Syntax

The basic syntax of the array_replace() function is given with:

  array_replace(array1array2, ...)

Parameters

The array_replace() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array in which elements are replaced.
array2 Optional. Specifies the array from which elements will be extracted.
... Optional. Specifies more array from which elements will be extracted. Values from later arrays overwrite the previous values.

 Example1 :

Output : 

Array
(
    [0] => Web
    [1] => Designing
    [2] => House
)

The array_replace() function replaces the values of the first array with the values from the following arrays in such a way that, 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 in 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 multiple arrays are passed for the replacement, they will be processed in order, the later arrays overwriting the previous values.

Example2 : 

The following example demonstrates what happens if a key exists in both first and second array, as well as if a key only exists in the first array and not in second array.

Output :

Array
(
    [a] => Web
    [b] => Designing
    [c] => House
    [0] => House
    [1] => Hello
)

Example3 : The following example shows what happens if a numeric key only exists in the second array.

Output : 

Array
(
    [0] => pineapple
    [1] => banana
    [2] => grape
    [3] => mango
    [4] => kiwi
)