PHP: How to overwrite values in one array with values from another without adding new keys to the ar
Posted
by Svish
on Stack Overflow
See other posts from Stack Overflow
or by Svish
Published on 2010-05-14T22:37:53Z
Indexed on
2010/05/14
23:44 UTC
Read the original article
Hit count: 208
I have an array with default settings, and one array with user-specified settings. I want to merge these two arrays so that the default settings gets overwritten with the user-specified ones.
I have tried to use array_merge
, which does the overwriting like I want, but it also adds new settings if the user has specified settings that doesn't exist in the default ones. Is there a better function I can use for this than array_merge
? Or is there a function I can use to filter the user-specified array so that it only contains keys that also exist in the default settings array?
(PHP version 5.3.0)
Example of what I want
$default = array('a' => 1, 'b' => 2);
$user = array('b' => 3, 'c' => 4);
// Somehow merge $user into $default so we end up with this:
Array
(
[a] => 1
[b] => 3
)
© Stack Overflow or respective owner