Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

How to extract a max() value from a collection at a given nested key ?

Hello,

I have a collection with several nested keys.

I need to extract a value being the max value.

$max = collect([
    ['foo' => 10, 'bar' => ['value' => 50, 'code' => 1]],
    ['foo' => 20, 'bar' => ['value' => 40, 'code' => 2]],
])->max('bar.value');

I'd like to retrieve the bar content for which the value is the max value.

'bar' => ['value' => 50, 'code' => 1]

Is it possible to do that via simple way with collections ?

Thanks for your help.

V

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Yes, you can achieve this using Laravel's collection methods. You can use the max method to find the maximum value and then use the first method to retrieve the corresponding item. Here's how you can do it:

$collection = collect([
    ['foo' => 10, 'bar' => ['value' => 50, 'code' => 1]],
    ['foo' => 20, 'bar' => ['value' => 40, 'code' => 2]],
]);

$maxValue = $collection->max('bar.value');

$maxItem = $collection->first(function ($item) use ($maxValue) {
    return $item['bar']['value'] === $maxValue;
});

$barContent = $maxItem['bar'];

print_r($barContent);

This will output:

Array
(
    [value] => 50
    [code] => 1
)

Explanation:

  1. We first find the maximum value in the nested bar.value using the max method.
  2. We then use the first method to find the first item in the collection where bar.value matches the maximum value.
  3. Finally, we extract the bar content from the item with the maximum value.

This approach ensures that you get the bar content for the item with the highest bar.value in a clean and efficient manner.

1 like
newbie360's avatar
$max = collect([
    ['foo' => 10, 'bar' => ['value' => 50, 'code' => 1]],
    ['foo' => 20, 'bar' => ['value' => 40, 'code' => 2]],
])->sortByDesc('bar.value')->first()['bar'];

output

Array
(
    ["value"] => 50
    ["code"] => 1
)
1 like
vincent15000's avatar

@newbie360 I finally decided to extract the state from the frontend with VueJS, because it has more sense to do like this according to some events sent via the websocket.

Please or to participate in this conversation.