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
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.