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',
],
]
2
Answers
Lets Combine Both Arrays:
First, combine both arrays => If they have the same key,
array_replace
will use the value from the second array.Apply a Callback Function: Use
array_map
with a custom callback function.This function will compare the values of the same keys in both arrays and keep the one with the higher value.// Combine arrays
// Apply callback function to keep higher values
Hope this should resolve.
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.