array_replace alternatives for earlier version of php?
I'm looking to use the array_replace function but the version of php I'm running doesn't support it. I was wondering if anyone new of any alternative ways of doing this?
The version of php I'm running is 5.2.17
I have an array and I just want to replace elements wi开发者_StackOverflow中文版th another array where the keys match.
I'm not able to update the version of php on the server btw :(
You mean something like this?
$array;
$replacement;
foreach ($array as $key => &$value) {
if (array_key_exists($key, $replacement)) {
$value = $replacement[$key];
}
}
or just
foreach ($replacement as $key => $value) {
$array[$key] = $value;
}
or maybe even
array_merge ($array, $replacement);
(I currently don't see any difference in the behaviour of array_merge()
and array_replace()
...)
If you want a real backport of this function you can use this code: http://www.php.net/manual/fr/function.array-replace.php#92549
if (!function_exists('array_replace'))
{
function array_replace( array &$array, array &$array1 )
{
$args = func_get_args();
$count = func_num_args();
for ($i = 0; $i < $count; ++$i) {
if (is_array($args[$i])) {
foreach ($args[$i] as $key => $val) {
$array[$key] = $val;
}
}
else {
trigger_error(
__FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
E_USER_WARNING
);
return NULL;
}
}
return $array;
}
}
Thanks to dyer85(at)gmail(dot)com
精彩评论