Home >Backend Development >PHP Tutorial >The php array_replace function replaces the elements of the first array with the passed array
array_replace() function replaces the value of the first array with the value of the following array. You can pass an array or multiple arrays to the function. This article explains how to use the php array_replace function through examples. Coders who need it can refer to it.
array_replace function syntax:
array array_replace ( array $array1 , array $array2 [, array $... ] )
array_replace() function replaces the value of the array1 array with the value of the same key of the subsequent array element. If a key exists in the first array and also exists in the second array, its value will be replaced by the value in the second array. If a key exists in the second array but not in the first array, the element will be created in the first array. If a key only exists in the first array, it will remain unchanged. If multiple replacement arrays are passed, they will be processed in order, and subsequent arrays will overwrite previous values.
array_replace() is non-recursive: it replaces the values of the first array regardless of the type in the second array.
Parameter description:
ParametersDescription
Array1 is necessary. Replace the value of this array. array2 Optional. Extract replacement values from this array. array3,... Optional. Specify multiple arrays to replace the values of array1 and array2, .... The values of the following array will overwrite the values of the previous array.Return valueReturns an array. If an error occurs, NULL will be returned. Instance:
<?php $base = array("orange", "banana", "apple", "raspberry"); $replacements = array(0 => "pineapple", 4 => "cherry"); $replacements2 = array(0 => "grape"); $basket = array_replace($base, $replacements, $replacements2); print_r($basket); ?>Run result:
Array ( [0] => grape [1] => banana [2] => apple [3] => raspberry [4] => cherry )