PHP array_replace() function
The array_replace()
function in PHP is used to replace the values of the first array with the values from subsequent arrays based on their keys. If a key from the first array exists in one of the subsequent arrays, the value from that subsequent array will overwrite the value in the first array.
Syntax:
Parameters:
- $array: The input array whose values will be replaced.
- $replacements: One or more arrays that provide the values to replace in the first array.
Return Value:
- Returns an array with the values from the first array replaced by the values from the subsequent arrays. The keys from the first array are preserved.
Example 1: Basic Replacement
In this example, we demonstrate how to use array_replace()
to replace specific values in an array.
Output:
In this case, the values for keys b
and c
in $array1
are replaced with the corresponding values from $array2
.
Example 2: Multiple Replacement Arrays
You can use array_replace()
with multiple replacement arrays. The function processes the replacements from left to right.
Output:
Here, the value for b
is replaced by blueberry
, the value for c
is replaced by cranberry
, and the new key d
with the value date
is added.
Example 3: Key Preservation
The keys from the original array are preserved even when replaced.
Output:
In this example, the value for key 1
in $array1
is replaced by "uno"
from $array2
, and a new key 3
with the value "tres"
is added.
Example 4: Handling Non-Existent Keys
If a key from the replacement arrays does not exist in the first array, it is simply added to the result.
Output:
Practical Usage:
array_replace()
is useful for:- Merging configurations where default values may be overwritten by user-defined values.
- Updating specific entries in a dataset while keeping others intact.
- Constructing complex arrays from simpler parts while maintaining key-value associations.
Summary:
array_replace($array, $replacements...)
replaces the values of the first array with those from subsequent arrays based on matching keys.- The function preserves the keys from the original array and returns a new array with the replacements applied.
- It is a flexible tool for managing and updating arrays in PHP, particularly when dealing with associative arrays.