In this tutorial, you will learn how to replace array values with another array’s values in PHP.
PHP has two inbuilt array functions – array_replace()
, and array_replace_recursive()
. With the help of these two functions, you can replace array values with another array’s values.
1. PHP array_replace() function
array_replace(array1, array2, array3, ...)
- The PHP
array_replace()
function only works with numeric and associative arrays. - It takes multiple parameters, and all the parameters must be an array. The first parameter is required, the others are optional.
- It replaces the values of the first array (
array1
) with the values from other given arrays. - This function returns a new array with the replaced values, it does not affect the original array.
<?php
$array1 = [1, 2, 3, 4, 5];
$array2 = [10, 12];
$newArray = array_replace($array1, $array2);
echo "<pre>";
print_r($newArray);
echo "</pre>";
Array
(
[0] => 10
[1] => 12
[2] => 3
[3] => 4
[4] => 5
)
Another Example
<?php
$array1 = ['Apple', 'Banana', 'Orange', 'Mango'];
$array2 = ['Pineapple', 'Strawberry'];
$array3 = ['Watermelon', 'Pear', 'Lychee'];
$newArray = array_replace($array1, $array2, $array3);
echo "<pre>";
print_r($newArray);
echo "</pre>";
Array
(
[0] => Watermelon
[1] => Pear
[2] => Lychee
[3] => Mango
)
2. PHP array_replace_recursive() function
PHP array_replace()
doesn’t work with multidimensional arrays, in this case you can use the array_replace_recursive()
function.
This function works similar to the array_replace()
function, except in the above case.
<?php
$array1 = [['Avocado', 'Apple'], 'Orange', ['Mango', 'Lemon']];
$array2 = [['Banana'], 'Watermelon', ['Lychee', 'Guava', 'Grapes']];
$newArray = array_replace_recursive($array1, $array2);
echo "<pre>";
print_r($newArray);
echo "</pre>";
Array
(
[0] => Array
(
[0] => Banana
[1] => Apple
)
[1] => Watermelon
[2] => Array
(
[0] => Lychee
[1] => Guava
[2] => Grapes
)
)