Laravel 5 Collections: Calculating the Minimum Value of a Collection With min

Laravel 5 Collections: Calculating the Minimum Value of a Collection With min

Laravel 5

The min method is the logical opposite of the max method, and accepts the same number of arguments. The min method can be used to retrieve the maximum value of the given $key. By default, the $key is null and will function in a similar way to PHP's min function.

Signature

public function min(
    $callback = null
);

Example Use

The following code example highlights the usage of min without specifying a $key:

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    0, 1, 2, 3, 4, 5
]);

// 0
$min = $collection->min();

After the above code has executed the $min variable would contain the value 0. The following code example shows how to use the min function when specifying a $key:

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    ['name' => 'Laravel', 'version' => '5.1'],
    ['name' => 'Lumen', 'version' => '5.0']
]);

// 5.0
$min = $collection->min('version');

// Laravel
$minName = $collection->min('name');

After the above code has executed the $min variable would contain the value 5.0 and the $minName variable would contain the value Laravel.

Start the Discussion

Leave a comment

Subscribe to our newsletter