Reputation: 5
<?php
$one = array(11 => 'a', 12 => 'b', 13 => 'c');
$two = array(14 => 'd', 15 => 'e');
print_r(array_merge($one, $two));
this return me:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
i would like receive:
Array
(
[11] => a
[12] => b
[13] => c
[14] => d
[15] => e
)
How can i merge two array with indexes? Is this possible? If yes, how?
Upvotes: 0
Views: 1210
Reputation: 2564
This is a possible solution.
$one = array(11 => 'a', 12 => 'b', 13 => 'c');
$two = array(14 => 'd', 15 => 'e');
function array_merge_values()
{
$args = func_get_args();
$result = $args[0];
for ($_ = 1; $_ < count($args); $_++)
foreach ($args[$_] as $key => $value)
{
if (array_key_exists($key,$result))
$result[$key] += $value;
else
$result[$key] = $value;
}
return $result;
}
var_dump(array_merge_values($one,$two));
Output
array (size=5)
11 => string 'a' (length=1)
12 => string 'b' (length=1)
13 => string 'c' (length=1)
14 => string 'd' (length=1)
15 => string 'e' (length=1)
Using print_r
Array
(
[11] => a
[12] => b
[13] => c
[14] => d
[15] => e
)
Upvotes: -2
Reputation: 343
Have you tried?
$three = $one + $two;
This should preserve the keys
Upvotes: 3
Reputation: 239521
Arrays with numeric keys will have their keys discarded by array_merge
. Instead, use the +
operator instead of array_merge
:
print_r $one + $two;
This produces:
Array
(
[11] => a
[12] => b
[13] => c
[14] => d
[15] => e
)
Alternatively, use string keys instead of numeric keys.
Upvotes: 6