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

itcan's avatar
Level 1

Collection min() max() help

Hey guys,

is there a way to return the array element/row with the min() / max() function? I have an array with prices and I want the min / max price, but I also want the whole array belonging to the min() / max() price..

$data = collect([
    0 => ['name' => 'test', 'price' => 100],
    1 => ['name' => 'test', 'price' => 200],
    2 => ['name' => 'test', 'price' => 300],
    3 => ['name' => 'test', 'price' => 10],
    4 => ['name' => 'test', 'price' => 600],
]);

$data->min('price')  => outputs 10
$data->max('price')  => outputs 600

But I also want to array row, like this:

$data->minArray('price')  => expected output ['name' => 'test', 'price' => 10]
$data->maxArray('price')  => expected output ['name' => 'test', 'price' => 600]
0 likes
2 replies
jlrdw's avatar

You could just have this in a table, perform a query to get min and max and just display the results of the queries. Even a temp table.

Recently I did an accounting app and for the checks

$stmt = $this->db->select("SELECT SUM(deposit) AS depsum FROM checks Where isclr = 0", array(), \PDO::FETCH_ASSOC);
        foreach ($stmt as $row) {
            $depsum = $row['depsum'];
        }

Another query was done for withdrawals, then I could add / substract as necessary.

You could do something like that (may even require 2 queries) one for min one for max. Just a thought.

TylerODonnell's avatar
Level 28

You could do something like this:

$min = $data->where('price', $data->min('price'))->first(); // ['name' => 'test', 'price' => 10]

$max = $data->where('price', $data->max('price'))->first(); // ['name' => 'test', 'price' => 600]
12 likes

Please or to participate in this conversation.