How to replace values in an array in PHP

To replace the values of an array, you can use the array_replace() function in PHP. This function replaces the values of one or more arrays with the values of another array.

Here is an example code:

$array1 = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$array2 = array('b' => 'blueberry', 'c' => 'coconut');

$result = array_replace($array1, $array2);

print_r($result);

Output result:

Array
(
    [a] => apple
    [b] => blueberry
    [c] => coconut
)

In the example above, the values of keys ‘b’ and ‘c’ in arrays $array1 and $array2 will be replaced by the corresponding values in $array2, resulting in a new array containing all key-value pairs.

Additionally, if you want to replace the values of multiple arrays, you can pass more parameters to the array_replace() function. For example:

$array1 = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$array2 = array('b' => 'blueberry', 'c' => 'coconut');
$array3 = array('c' => 'cranberry', 'd' => 'durian');

$result = array_replace($array1, $array2, $array3);

print_r($result);

Output:

Array
(
    [a] => apple
    [b] => blueberry
    [c] => cranberry
    [d] => durian
)

In this example, the values of keys “b” and “c” in arrays $array1, $array2, and $array3 will be replaced by the corresponding values of those keys in the last array. The final result is a new array containing all key-value pairs.

bannerAds