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_map
and array_column
:
$keys = array_keys(reset($arr) ?: []);
$res = array_combine(
$keys,
array_map(fn ($k) => max(array_column($arr, $k)), $keys)
);
print_r($res);
Output:
Array
(
[2] => 6
[5] => 3
)
Demo on 3v4l.org
For those using PHP prior to 7.4, you can replace the arrow function with
function ($k) use ($arr) { return max(array_column($arr, $k)); }
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.