PHP array_replace() Function
Quick summary: The PHP array_replace() function replaces values from the first array with values from following arrays.
PHP array_replace() Syntax
array_replace(array $array, array ...$replacements): array
PHP
PHP array_replace() Basic examples
$base = ['a'=>1,'b'=>2];
$replace = ['b'=>3];
print_r(array_replace($base, $replace));
PHP
Output:
Array ( [a] => 1 [b] => 3 )
Replaces matching keys.
PHP array_replace() Real-world usage
$defaults = ['host'=>'localhost','port'=>3306];
$config = ['port'=>3307];
$final = array_replace($defaults, $config);
print_r($final);
PHP
Output:
Array ( [host] => localhost [port] => 3307 )
Override default configuration values.
PHP array_replace() Edge cases
print_r(array_replace(['a'=>1], ['b'=>2]));
PHP
Output:
Array ( [a] => 1 [b] => 2 )
Adds new keys if not present.
PHP array_replace() Common mistakes
Confusing with array_merge()
array_replace() preserves numeric keys.
Incorrect
array_merge([1,2],[3]);
Correct
array_replace([1,2],[3]);
array_merge() reindexes numeric keys.
PHP array_replace() Frequently Asked Questions
What does array_replace() do?
Replaces values of the first array with values from following arrays.
Use case?
Override default values.
Handles keys?
Yes.
Difference from array_merge()?
Does not reindex numeric keys.
Return type?
Array.
Common mistake?
Expecting merge behavior.
Performance?
Fast.
Safe?
Yes.
Handles nested arrays?
No.
Alternative?
array_merge().
Best practice?
Use for overriding configs.
Modifies original?
No.