Im newbie here and i try to ask my question directly! My problem it's based on array merge in function.
I have this code:
GameFiles(array("gid" => "1", "sid" => "1", "expirecache" => "0"));
GameFiles(array("gid" => "1", "sid" => "1"));
function GameFiles($params) {
$default = array('skipcache' => false, 'expirecache' => 86400, 'os' => null);
$params = array_merge($default, $params);
var_dump($params);
}
And i get this output:
array(5) {
["skipcache"]=>
bool(false)
["expirecache"]=>
string(1) "0"
["os"]=>
NULL
["gid"]=>
string(1) "1"
["sid"]=>
string(1) "1"
}
array(5) {
["skipcache"]=>
bool(false)
["expirecache"]=>
int(86400)
["os"]=>
NULL
["gid"]=>
string(1) "1"
["sid"]=>
string(1) "1"
}
The issues is this 2 array in output. I want to merge all array in 1 because if you look on " Key " all is same in 3 array.
If you look on this 2 sender :
GameFiles(array("gid" => "1", "sid" => "1", "expirecache" => "0"));
GameFiles(array("gid" => "1", "sid" => "1"));
This will go in GameFile($params) and I set default other array but I want to merge all array in one array !
Thanks
Regards
Sorry - I can't comment but David Kmenta is correct - you don't really need to have a function. There is one basic problem with your existing code: any time you call GameFiles, you are merging your $default array with the $params array. You're never merging the two arrays you are trying to merge.
To make this clearer, here's what is happening when you unwrap it from your function:
$default = array('skipcache' => false, 'expirecache' => 86400, 'os' => null);
$params1 = array("gid" => "1", "sid" => "1", "expirecache" => "0");
var_dump(array_merge($default, $params1));
$params2 = array("gid" => "1", "sid" => "1");
var_dump(array_merge($default, $params2));
You are just printing out two separate arrays. If you have a default array and need to merge it, you just use array_merge() twice like
$default = array('skipcache' => false, 'expirecache' => 86400, 'os' => null);
$params1 = array_merge($default, array("gid" => "1", "sid" => "1", "expirecache" => "0"));
$result = array_merge($params1, array("gid" => "1", "sid" => "1"));
var_dump($result);
Or, even possibly more sketchy/useless/overkill if you're lazy and don't want to constantly do re-assignment:
$default = function($arrOne, $arrTwo){
return array_merge($arrOne, $arrTwo);
};
$param1 = array('skipcache' => false, 'expirecache' => 86400, 'os' => null);
$param2 = array("gid" => "1", "sid" => "1", "expirecache" => "0");
$param3 = array("gid" => "1", "sid" => "1");
var_dump($default($default($param, $param2), $param3));