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

后端 未结 5 1905
野的像风
野的像风 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.

     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.

提交回复
热议问题