array_replace(array $array1, array ...$arrays): array
This function returns an array where values from the second (or subsequent) array replace the matching keys in the first array. If a key is not found in subsequent arrays, it is not replaced.
$array1 = [0 => "red", 1 => "green", 2 => "blue"];
$array2 = [0 => "orange", 2 => "black"];
$result = array_replace($array1, $array2);
print_r($result);
Array
(
[0] => orange
[1] => green
[2] => black
)
$array1 = ['name' => 'John', 'age' => 30];
$array2 = ['name' => 'Doe', 'city' => 'New York'];
$result = array_replace($array1, $array2);
print_r($result);
Array
(
[name] => Doe
[age] => 30
[city] => New York
)
$array1 = [1 => "apple", 2 => "banana"];
$array2 = [2 => "grape"];
$array3 = [1 => "orange"];
$result = array_replace($array1, $array2, $array3);
print_r($result);
Output
Array
(
[1] => orange
[2] => grape
)
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.