Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge "Defaults" array with "Input" array? PHP Which Function?

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?

like image 492
Orangeman555 Avatar asked May 06 '13 04:05

Orangeman555


People also ask

Which will merge two arrays in PHP?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.

What does the array_merge () function do?

The array_merge() function merges one or more arrays into one array. Tip: You can assign one array to the function, or as many as you like. Note: If two or more array elements have the same key, the last one overrides the others.

What is the difference between array_merge () and Array_merge_recursive () in PHP?

Definition and Usage The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

Which function combines for merge two or more arrays?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


2 Answers

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.

like image 154
Riccardo Galli Avatar answered Sep 29 '22 23:09

Riccardo Galli


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

like image 20
Vladyslav Savchenko Avatar answered Sep 29 '22 22:09

Vladyslav Savchenko