PHP array_replace()Functions

PHP Array 参考手册Complete PHP Array Reference

Examples

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));
?>

Run example »

Definition and Usage

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

Tip:You can pass one array or multiple arrays to the function.

If a key exists in the first array array1 and also 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 exists only in the first array array1, it will remain unchanged. (See Example 1 below)

If a key exists in the second array array2 but not in the first array array1, this element will be created in the first array array1. (See Example 2 below)

If multiple replacement arrays are passed, they will be processed in order, and the values from later arrays will overwrite the values from earlier arrays. (See Example 3 below)

Tip:Usearray_replace_recursive()to recursively replace the values of the first array with the values from subsequent arrays.


Syntax

array_replace(array1,array2,array3...)

Parameter Description
array1 Required. Specifies an array.
array2 Optional. Specifies an array of valuesarray1to replace.
array3,... Optional. Specifies multiple arrays of valuesarray1andarray2, ...to replace. Values from later arrays will overwrite the values from earlier arrays.

Technical Details

Return value: Returns the replaced array, or NULL if an error occurs.
PHP Version: 5.3.0+


More Examples

Example 1

If a key exists in the first array array1 and also 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 exists only 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));
?>

Run example »

Example 2

If a key exists in the second array array2 but not in the first array array1, this 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));
?>

Run example »

Example 3

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));
?>

Run example »

Example 4

Using numeric keys - If a key exists in the second array array2 but not in the first array array1, this 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));
?>

Run example »


PHP Array 参考手册Complete PHP Array Reference Other Extensions