0

I have an array like:

Array
(
 [0] => Array
    (
        [Name] => Name1
        [Totaal] => 13
    )

[1] => Array
    (
        [Name] => Name2
        [Totaal] => 117
    )

[2] => Array
    (
        [Name] => Name3
        [Totaal] => 39
    )
)

Now i would like to get the the array with the highest "Totaal" In this example, i would like to have returned:

Array
    (
        [Name] => Name2
        [Totaal] => 117
    )

I have found methods like:

max(array_column($arr, 'Totaal'));

But this only returns the max value, and not the array itself. Any ideas?

Timberman
  • 647
  • 8
  • 24
  • 1
    That looks very much like https://stackoverflow.com/questions/17339421/find-highest-value-in-multidimensional-array. The answer you've shown may not get what you want but do any of the others solve your problem? – Nigel Ren Nov 19 '20 at 13:22
  • I know, i have taken the array from that question. The question itself is different though. I'll edit the array to not cause any confusion – Timberman Nov 19 '20 at 13:22
  • Don't know about the code. But I think it's possible to sort the arrays on the Total entry so the highest value goes first. After that just only return the first entry – Patrick de Ronde Nov 19 '20 at 13:24
  • 1
    There are great solutions to this in that duplicate, for example https://stackoverflow.com/a/17339531/476. – deceze Nov 19 '20 at 13:25

1 Answers1

0

Try this:

$array = [
    [
        'key' => 'key1',
        'value' => 13,
    ],
    [
        'key' => 'key2',
        'value' => 117,
    ],
    [
        'key' => 'key3',
        'value' => 39

    ]
];

$result = array_reduce(
    $array,
    fn(array $carry, array $item) => $carry === null || $item['value'] > $carry['value'] ? $item : $carry,
    null
);

var_dump($result);

// array(2) {
//  ["key"]=>
//  string(4) "key2"
//  ["value"]=>
//  int(117)
// }
Josef Sábl
  • 7,538
  • 9
  • 54
  • 66