I want to merge two arrays by keeping higher value if keys are the same in PHP. Also would like to keep array keys.
I am not looking for a solution to manually go through arrays and compare values, I was thinking about some combination with array_replase and callback call if possible.
Example:
$array1 = [
4 => [
'name' => 'John',
'value' => '5',
],
5 => [
'name' => 'Michael',
'value' => '4',
],
6 => [
'name' => 'Steve',
'value' => '7',
],
]
$array2 = [
5 => [
'name' => 'Peter',
'value' => '6',
],
6 => [
'name' => 'Glen',
'value' => '3',
],
]
Expected result:
$result = [
4 => [
'name' => 'John',
'value' => '5',
],
5 => [
'name' => 'Peter',
'value' => '6',
],
6 => [
'name' => 'Steve',
'value' => '7',
],
]
Just to show you that this can also be solved with a simple
foreach
loop:You could replace the
foreach
with aarray_walk
:which functionally does exactly the same, but is it as easy to read? I don't think so.