PHP Tutorial - PHP array_replace() Function






Definition

The array_replace() function replaces the values of the first array with the values from following arrays.

Syntax

PHP array_replace() Function has the following syntax.

array_replace(array1,array2,array3...)

Parameter

ParameterIs RequiredDescription
array1Required.Array to replace
array2Optional.Array to replace array1
array3,...Optional.Array to replace array1 and array2, etc.

Example 1

Replaces the values of the first array with the values from following arrays


<?php
    $a1=array("A","C");
    $a2=array("B","D");
    print_r(array_replace($a1,$a2));
?>

The code above generates the following result.





Example 2

If a key from array1 exists in array2, and if the key only exists in array1:


<?php
    $a1=array("p"=>"PHP","j"=>"Java");
    $a2=array("p"=>"Python");
    print_r(array_replace($a1,$a2));
?>

The code above generates the following result.

Example 3

If a key exists in array2 and not in array1:


<?php
    $a1=array("a"=>"red","java2s.com");
    $a2=array("c"=>"orange","d"=>"burgundy");
    print_r(array_replace($a1,$a2));
?>

The code above generates the following result.





Example 4

Using three arrays - the last array ($a3) will overwrite the previous ones ($a1 and $a2):


<?php
    $a1=array("A","B");
    $a2=array("A","java2s.com");
    $a3=array("B","F");
    print_r(array_replace($a1,$a2,$a3));
?>

The code above generates the following result.

Example 5

Using numeric keys - If a key exists in array2 and not in array1:


<?php
    $a1=array("A","B","C","D");
    $a2=array(0=>"java2s.com",30=>"PHP");
    print_r(array_replace($a1,$a2));
?>

The code above generates the following result.