PHP array_replace() Function

PHP array_replace() function is used to replace the values of an array with the values from one or more arrays based on key/index.

Points to remember:

  • If a key from the first array exists in the second array, its value will be replaced by the value from the second array.
  • If a key from the second array does not exist in the first array, it will be added to the first array along with its corresponding value from the second array.
  • If a key only exists in the first array, it will be left unchanged.

Syntax

array_replace($array1,$array2,..., $arrayn)

Parameters

  1. $array1(required): It specifies an array.
  2. $array2(optional): This specifies an array that will replace the values of array1.

Return value

It returns the replaced array. If any error occurs during function execution, it returns NULL.

Visual RepresentationVisual Representation of PHP array_replace() Function

Example 1: How to Use array_replace

<?php

$brandsA = [
 'a' => 'AppDividend',
 'b' => 'Hermès',
 'c' => 'Gucci'];

$brandsB = [
 'b' => 'Tesla',
 'c' => 'Coca-cola',
 'd' => 'Google'];

$replaced = array_replace($brandsA, $brandsB);
print_r($replaced);

Output

Array
(
 [a] => AppDividend
 [b] => Tesla
 [c] => Coca-cola
 [d] => Google
)

In the above example, “Hermès” is replaced by “Tesla” and “Gucci” is replaced by “Coca-cola”.

Example 2: If the key exists in array2 and not in array1Visual Representation of If the key exists in array2 and not in array1

<?php

$brandsA = [
 'a' => 'AppDividend',
 'b' => 'Hermès',
 'c' => 'Gucci'];

$brandsB = [
 'x' => 'X',
 'y' => 'Yahoo',
 'z' => 'Rolex'];

$replaced = array_replace($brandsA, $brandsB);
print_r($replaced);

Output

Array
(
 [a] => AppDividend
 [b] => Hermès
 [c] => Gucci
 [x] => X
 [y] => Yahoo
 [z] => Rolex
)

Example 3: Using three arrays

<?php

$brandsA = [
 'a' => 'AppDividend',
 'b' => 'Hermès',
 'c' => 'Gucci'];
 
$brandsB = [
 'x' => 'X',
 'y' => 'Yahoo',
 'c' => 'Rolex'];
 
$brandsC = [
 'y' => 'Reddit',
 'z' => 'Google'
];

$replaced = array_replace($brandsA, $brandsB, $brandsC);
print_r($replaced);

Output

Array
(
 [a] => AppDividend
 [b] => Hermès
 [c] => Rolex
 [x] => X
 [y] => Reddit
 [z] => Google
)

Example 4: Using Indexed ArrayVisual Representation of Using Indexed Array

<?php

$arrA = ['disney', 'netflix', 'hulu'];
$arrB = ['sports', 'games', 'discovery'];

$replaced = array_replace($arrA, $arrB);
print_r($replaced);

Output

Array
(
 [0] => sports
 [1] => games
 [2] => discovery
)

Since the arrays are indexed numerically and both arrays have the same keys (0, 1, 2), the values in $arrA will be replaced by the values in $arrB.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.