PHP array_replace() function

Example

Use the values of the second array ($a2) to replace the values of the first array ($a1):

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>

Run Instance

Definition and usage

The array_replace() function uses the values of the subsequent array to replace the values of the first array.

Hint:You can pass an array or multiple arrays to the function.

If a key exists in the first array array1 Also exists in the second array array2The first array array1 will be replaced by the second array array2 to replace the value. If a key only exists in the first array array1It will remain unchanged. (See the example below 1)

If a key exists in the second array array2If it does not exist in the first array array1If it exists in the first array array1 to create this element. (See the example below 2)

If multiple replacement arrays are passed, they will be processed in order, and the values of the subsequent array will overwrite the values of the previous array. (See the example below 3)

Hint:Please use array_replace_recursive() to recursively use the values of the subsequent array to replace the values of the first array.

Syntax

array_replace(array1,array2,array3...)
Parameter Description
array1 Required. Specify the array.
array2 Optional. Specify the replacement array1 The array of values.
array3,... Optional. Specify multiple replacements array1 And array2The array of values of ... . The values of the subsequent array will overwrite the values of the previous array.

Technical details

Return value: Ibabalik ang napalitan na array, kung may mali ay ibabalik NULL.
PHP Version: 5.3.0+

Mga Higit pang Mga Halimbawa

Example 1

Kung ang isang key ay nasa array1 Sa gayon din ay nasa array2 Sa, ang halaga ng unang array ay papalitan ng halaga ng ikalawang array:

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("a"=>"orange","burgundy");
print_r(array_replace($a1,$a2));
?>

Run Instance

Example 2

Kung ang isang key ay nasa ikalawang array subalit wala sa unang array:

<?php
$a1=array("a"=>"red","green");
$a2=array("a"=>"orange","b"=>"burgundy");
print_r(array_replace($a1,$a2));
?>

Run Instance

Example 3

Mga tatlong array - Ang huling array ($a3) ay papalitan ng mga naunang array ($a1 at $a2):

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
$a3=array("orange","burgundy");
print_r(array_replace($a1,$a2,$a3));
?>

Run Instance

Example 4

Mga numerical na key - Kung ang isang key ay nasa ikalawang array subalit wala sa unang array:

<?php
$a1=array("red","green","blue","yellow");
$a2=array(0=>"orange",3=>"burgundy");
print_r(array_replace($a1,$a2));
?>

Run Instance