I have two arrays with the same keys, but different values.
Example:
(
"2"=> 6,
"5"=> 1
),
(
"2"=> 1,
"5"=> 3
)
I want to create a new array with the same keys, but replace the highest values like this:
(
"2"=> 6,
"5"=> 3
)
What should I do?
You need to iterate getting the maximum value for each key, which you can do with a combination of
array_keys,array_combine,array_mapandarray_column:Output:
Demo on 3v4l.org
For those using PHP prior to 7.4, you can replace the arrow function with
Note that this code assumes that all the sub-arrays have the same keys or some subset of the keys of the first sub-array.