Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Lets say you are having a user provide information.

Array 1

But not all is required. So you have defaults.

Array 2

Does PHP have a function which will overwrite all array values of Array 2 based on if they are supplied in Array 1, and not empty?

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

I'm not sure either of these answers are helping you out (they didn't help me) especially for the case when your "defualts" may be an associative array more than one level deep.

I think what you are looking for is array_replace_recursive.
$finalArray = array_replace_recursive(array $defaults, array $inputOptions)

heres an example that takes an optional array of options to a function and does some processing based on the result of those options "opts" and the defaults which you specify:

function do_something() {
    $args = func_get_args();
            $opts = $args[0] ? $args[0] : array();

    $defaults = array(
        "second_level" => array(
                    "key1" => "val1",
                    "key2" => "val2"
                ),
        "key1" => "val1",
        "key2" =>  "val2",
        "key3" => "val3"
    );

    $params = array_replace_recursive($defaults, $opts);
    // do something with these merged parameters
}

Check it out here

share|improve this answer
    
That would have been great! TY –  Orangeman555 Dec 18 '13 at 6:47
add comment

array_merge() is exactly what you are looking for.

share|improve this answer
add comment

You can just do something like

foreach($array1 as $key=>$value) $array2[$key]=$value;
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.