Is there a more efficient way to code this than what I have?

Posted on 16th Feb 2014 by admin

I have three associative arrays.

$combinedSettings
$userSettings
$defaultSettings

My function must combine the key and value from $userSettings and $defaultSettings into the $combinedSettings array.

$userSettings will always contain more keys than $defaultSettings will ever have.

So every once in a while there is an extra key and of course it's value in the $userSettings array than in the $defaultSettings array.

If the value of a key in $userSettings is empty we then use the value for the same key in the $defaultSettings. Every key in $defaultSettings will always be present in $userSettings. $userSettings just adds a few extra keys and their values.

Below is my working code but I am wondering if there is some way to make it more efficient, faster, perhaps with less code. It looks rather clutzy to me. Rather bloated.

Code: while (list($userKey, $userValue) = each($userSettings)) {
while ($defaultKey = key($defaultSettings)) {
$defaultValue = current($defaultSettings);
if ($userKey === $defaultKey) {
if ($userValue === "") {
$combinedSettings[$defaultKey] = $defaultValue;
} else {
$combinedSettings[$userKey] = $userKey;
}
next($defaultSettings); // to allow key() to work properly above.
} else { // add userSettings setting and value to combinedSettings and leave
// defaultSettings where it is.
$combinedSettings[$userKey] = $userValue;
}
break;
}
}

Thanks.

Other forums