← Back to Chapters

PHP array_replace & array_replace_recursive

? PHP array_replace & array_replace_recursive

? Quick Overview

PHP provides functions to replace values in arrays with new values. These functions are array_replace() and array_replace_recursive(). The main difference is that array_replace() works only on the top level of an array, whereas array_replace_recursive() works on all levels.

? Key Concepts

  • array_replace() replaces values using matching keys at the first level.
  • array_replace_recursive() replaces values in nested arrays.
  • Original arrays remain unchanged; a new array is returned.

⚡ Syntax / Theory

? View Code Example
// Basic syntax for array_replace
array_replace($array1, $array2, ...);
? View Code Example
// Basic syntax for array_replace_recursive
array_replace_recursive($array1, $array2, ...);

? Code Example 1: array_replace()

? View Code Example
// Replace top-level values using array_replace
 "red", "banana" => "yellow", "cherry" => "red");
$replacement = array("banana" => "green", "cherry" => "pink");
print_r(array_replace($fruits, $replacement));
?>

Live Output / Explanation

The values of banana and cherry are replaced, while apple remains unchanged.

? Code Example 2: array_replace_recursive()

? View Code Example
// Replace nested values using array_replace_recursive
 "red", "tropical" => array("banana" => "yellow", "mango" => "orange"));
$replace = array("tropical" => array("banana" => "green"));
print_r(array_replace_recursive($fruit, $replace));
?>

Live Output / Explanation

The nested banana value inside tropical is updated, while other values remain the same.

? Use Cases

  • Updating configuration arrays.
  • Overriding default values.
  • Working with nested data structures.

✅ Tips & Best Practices

  • Use array_replace() for simple, flat arrays.
  • Use array_replace_recursive() for multidimensional arrays.
  • Pass multiple replacement arrays when needed.

? Try It Yourself

  • Create a multidimensional product array and update prices.
  • Modify a shopping cart using array_replace().
  • Compare results of both functions.