PASSWORD RESET

Your destination for complete Tech news

How to get the maximum value of a given key in Laravel collection?

2.2K 0
< 1 min read

To get the maximum value of a given key in a Laravel collection, you can use the max method. This method will return the maximum value of the items in the collection based on a given key.

Here’s an example:

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$max = $collection->max('age');

// $max is now 35

You can also pass a callback to the max method to specify a custom comparison function:

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$max = $collection->max(function ($item) {
    return $item['age'] * -1;
});

// $max is now ['name' => 'Alice', 'age' => 25]

Note that the max method will return the whole item, not just the value of the given key. If you want to get only the value, you can use the pluck method to extract the values before calling the max method:

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$max = $collection->pluck('age')->max();

// $max = 35;

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.