Applications often start with a set of default options and then allow users to change some of them. You might also combine product information, configuration files, or API data without rebuilding an entire array manually.
The array_replace() function provides a simple way to copy an array and replace values by matching keys.
What Is array_replace() in PHP?
array_replace() creates a new array using the first array as its starting point. Each additional array supplies values that replace entries with the same keys. Keys that do not already exist are added to the result.
Its syntax is:
array_replace(
array $array,
array ...$replacements
): array
The parameters are:
$array— The initial array whose entries are copied into the result....$replacements— One or more arrays supplying replacement values. Later arrays have higher priority.
The function returns a new array. The original input arrays are not modified.
Important: Comparison is based on keys, not on matching values. If two arrays contain the same key, the replacement value wins even when it is false, null, or an empty string.
Example 1: Replacing Values with Matching Keys
Suppose an application provides default settings but lets a user override two of them.
<?php
$defaultSettings = [
"theme" => "light",
"language" => "en",
"notifications" => true
];
$userSettings = [
"theme" => "dark",
"notifications" => false
];
$finalSettings = array_replace($defaultSettings, $userSettings);
print_r($finalSettings);
Output:
Array
(
[theme] => dark
[language] => en
[notifications] =>
)
The user settings replace theme and notifications. The language value stays unchanged because the replacement array does not contain that key.
In the print_r() output, the blank value after [notifications] represents the boolean false. It does not mean the entry was removed.
Example 2: Applying Multiple Replacement Arrays
When you provide multiple replacement arrays, PHP processes them from left to right. The last array containing a key determines its final value.
<?php
$basePrices = [
"notebook" => 12,
"pen" => 3
];
$weekendPrices = [
"notebook" => 10,
"folder" => 5
];
$memberPrices = [
"notebook" => 8
];
$finalPrices = array_replace(
$basePrices,
$weekendPrices,
$memberPrices
);
print_r($finalPrices);
Output:
Array
(
[notebook] => 8
[pen] => 3
[folder] => 5
)
The weekend price changes notebook to 10, but the later member price changes it again to 8. The pen price remains unchanged, and folder is added because its key did not exist in the base array.
Practical Example: Updating Allowed User Preferences
Imagine a settings page where users can change their theme and the number of items displayed per page. The application should also keep its existing defaults, without accepting unexpected keys such as role.
Create a file named user-preferences.php:
<?php
declare(strict_types=1);
$defaultPreferences = [
"theme" => "light",
"items_per_page" => 10,
"email_updates" => true
];
// These values might come from a validated settings form.
$submittedPreferences = [
"theme" => "dark",
"items_per_page" => 25,
"role" => "admin"
];
// Accept only settings that exist in the defaults.
$allowedPreferences = array_intersect_key(
$submittedPreferences,
$defaultPreferences
);
// Replace defaults with the approved preferences.
$preferences = array_replace(
$defaultPreferences,
$allowedPreferences
);
foreach ($preferences as $settingName => $settingValue) {
$displayValue = is_bool($settingValue)
? ($settingValue ? "Yes" : "No")
: (string) $settingValue;
$displayLine = $settingName . ": " . $displayValue;
echo "<p>" . htmlspecialchars(
$displayLine,
ENT_QUOTES,
"UTF-8"
) . "</p>";
}
Browser output:
theme: dark
items_per_page: 25
email_updates: Yes
array_intersect_key() first removes fields not present in the defaults. Then array_replace() updates the permitted preferences and keeps values the user did not submit.
The loop converts the values into readable text and escapes them before placing them in HTML. That matters because data displayed in a webpage should be encoded for its output context.
Security note: An allowlist of field names is not enough by itself. Validate each value, enforce user permissions, and never use a simple merge to grant roles or other sensitive capabilities.
Important Behavior and Edge Cases
- New keys are added: A replacement key does not need to exist in the first array.
- Later arrays win: The rightmost array containing a key supplies its final value.
- Values are not compared: A replacement value of
nullorfalsestill overwrites the earlier value. - Numeric keys are preserved: Numeric indexes are matched as keys rather than appended or automatically renumbered.
- Nested arrays are replaced as a whole: The function does not merge nested structures recursively.
- Original arrays stay unchanged: The result is a separate array value.
- At least two arrays: The first array and at least one replacement array are required.
What Happens with Numeric Keys?
This matters when working with indexed arrays. Unlike array_merge(), array_replace() does not reindex numeric keys.
<?php
$originalItems = ["apple", "pear"];
$replacementItems = [1 => "plum", 4 => "melon"];
print_r(array_replace($originalItems, $replacementItems));
Output:
Array
(
[0] => apple
[1] => plum
[4] => melon
)
The index 1 is replaced and index 4 is added. PHP does not fill missing indexes 2 or 3.
What About Nested Arrays?
If the original and replacement arrays both contain an array under the same key, the nested array is replaced entirely.
<?php
$defaults = [
"mail" => ["host" => "localhost", "port" => 25]
];
$overrides = [
"mail" => ["port" => 587]
];
print_r(array_replace($defaults, $overrides));
Output:
Array
(
[mail] => Array
(
[port] => 587
)
)
Notice that host disappears. To preserve nested entries while updating individual nested values, consider array_replace_recursive(), but check its behavior carefully when nested arrays contain indexed lists.
array_replace() vs Related Functions
| Function | Main Behavior |
|---|---|
array_replace() | Replaces values by matching keys; keeps numeric indexes. |
array_replace_recursive() | Applies replacements inside nested arrays as well. |
array_merge() | Overwrites matching string keys but appends and renumbers numeric-keyed values. |
array_merge_recursive() | Combines matching values recursively, often creating arrays of values rather than simply replacing them. |
array_intersect_key() | Selects entries whose keys exist in another array; useful for filtering keys before replacement. |
Choose array_replace() when your goal is to apply clear, key-based overrides while keeping the original key structure.
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Expecting replacement arrays to modify the original variable | Assign the returned array to a variable, or assign it back to the original variable. |
| Assuming a new replacement key will be ignored | Remember that keys missing from the first array are added; filter keys first when necessary. |
Using array_replace() to merge nested settings | Use an explicit nested merge or examine array_replace_recursive(). |
| Expecting numeric values to be appended | Understand that numeric keys are replaced by index. Use array_merge() when appending is appropriate. |
| Allowing raw form data to override protected configuration | Use an allowlist, validate values, and check authorization before applying overrides. |
Key Takeaways
array_replace()creates a new array with key-based replacements.- Later replacement arrays take priority when keys repeat.
- New keys are added, while keys not mentioned remain unchanged.
- Numeric keys are matched directly instead of being renumbered.
- Nested arrays are replaced as complete values, not merged recursively.
- Filter and validate user-controlled data before applying it to application settings.
PHP array_replace() is especially useful for default configuration values, user preferences, and other situations where one array provides a starting point and later arrays supply overrides. Understanding key behavior and nested arrays helps prevent unexpected results.