array_replace(): replace array values

The array_replace() function in PHP is used to replace the values of the first array with the values from subsequent arrays. If a key exists in multiple arrays, the value from the last array will replace the earlier one.

Syntax

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.

Example 1: Replacing Simple Indexed Array Values

$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
)

Example 2: Replacing Values in an Associative Array

$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
)

Example 3: Using Multiple Replacement Arrays

$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
)

Conclusion

The array_replace() function provides a flexible way to replace values in an array using one or more replacement arrays. It is especially useful when handling configuration settings or merging data where certain values need to be overwritten.
array_splice(): Modifying Arrays in PHP Difference between arrays considering values
Array REFERENCE
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer