skip to Main Content

I have two array with same key but diff value
example :

(
    "2"=> 6,
    "5"=> 1
),
(
    "2"=> 1,
    "5"=> 3
)

I want to create new array with the same key but replace highest value
like this

 (
    "2"=> 6,
    "5"=> 3
)

what should I do

2

Answers


  1. Use a nested loop, check if the key is encountered for the first time or if the stored value for that key is less than the current value.

    Code: (Demo)

    $result = [];
    foreach ($array as $row) {
        foreach ($row as $k => $v) {
            if (!isset($result[$k]) || $result[$k] < $v){
                $result[$k] = $v;
            }
        }
    }
    var_export($result);
    
    Login or Signup to reply.
  2. 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(
            function ($k) use ($arr) { return max(array_column($arr, $k)); },
            $keys)
        );
    print_r($res);
    

    Output:

    Array
    (
        [2] => 6
        [5] => 3
    )
    

    Demo on 3v4l.org

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search