Merge “Defaults” array with “Input” array? PHP Which Function?

后端 未结 5 1888
野的像风
野的像风 2021-02-14 15:43

Lets say you are having a user provide information.

Array 1

But not all is required. So you have defaults.

Array 2


        
相关标签:
5条回答
  • 2021-02-14 16:19

    If you just want to keep the options that you expect and discard the rest you may use a combination of array_merge and array_intersect_key.

    <?php
    
    function foo($options) {
        $defaults = [
            'a' => 1,
            'b' => null,
        ];
    
        $mergedParams = array_merge(
            $defaults,
            array_intersect_key($options, $defaults)
        );
    
        return $mergedParams;
    }
    
    
    var_dump(foo([
        'a' => 'keep me',
        'c' => 'discard me'
    ]));
    
    // => output
    //
    // array(2) {
    //   ["a"]=>
    //   string(7) "keep me"
    //   ["b"]=>
    //   NULL
    // }
    

    If you instead want to keep any extra key then array_merge($defaults, $options) will do just fine.

    0 讨论(0)
  • 2021-02-14 16:19

    I think what you are looking for is array_replace_recursive, especially for the case when your "defualts" may be an associative array more than one level deep.

    $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
    }
    

    The php.net reference document is here

    0 讨论(0)
  • 2021-02-14 16:22
    $defaults = array(
        'some_key_1'=>'default_value_1',
        'some_key_2'=>'default_value_2',
    );
    
    $inputs = array_merge($defaults, $inputs)
    

    Note that if the $inputs array contains keys not in the $defaults array they will be added in the result.

    0 讨论(0)
  • 2021-02-14 16:27

    array_merge() is exactly what you are looking for.

    0 讨论(0)
  • 2021-02-14 16:40

    You can just do something like

    foreach($array1 as $key=>$value) $array2[$key]=$value;
    
    0 讨论(0)
提交回复
热议问题