📜  laravel collection min - PHP (1)

📅  最后修改于: 2023-12-03 15:02:34.680000             🧑  作者: Mango

Laravel Collection Min - PHP

Introduction

Laravel is a popular PHP framework that provides various tools and functionalities to make web development easier and faster. Laravel Collection is one of the powerful features of Laravel that provides an easy way to work with arrays and objects.

In this article, we will explore how to use the Laravel Collection min method to get the minimum value from a collection of values.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • PHP 7.0 or higher
  • Laravel 5.0 or higher
Laravel Collection Min

The min method of Laravel Collection returns the minimum value of a given collection of values. It extracts the values from each item in the collection and compares them to find the minimum value.

Parameters

The min method takes an optional parameter that specifies the key to examine when determining the minimum value. By default, it compares the values themselves, but you can pass a closure that returns the value to be compared.

Syntax

The syntax for the min method is as follows:

$collection->min($callback);

Here, $collection is the instance of Laravel Collection, and $callback is an optional closure that returns the value to be compared.

Examples

Let's take a look at some examples to see how the min method can be used.

Simple Example

The following code demonstrates how to use the min method to find the minimum value in a collection of numbers.

use Illuminate\Support\Collection;

$collection = collect([2, 4, 6, 8]);
$minValue = $collection->min();

echo $minValue; // Output: 2

Here, the min method returns the minimum value of 2 from the collection.

Example with Callback

The following code uses a callback function to find the minimum value of a collection of items.

$collection = collect([
    ['name' => 'John', 'age' => 21],
    ['name' => 'Doe', 'age' => 30],
    ['name' => 'Smith', 'age' => 25],
]);

$minAge = $collection->min(function ($item) {
    return $item['age'];
});

echo $minAge; // Output: 21

Here, the min method uses the callback function to extract the age property of each item in the collection and find the minimum value of 21.

Conclusion

The min method of Laravel Collection provides an easy way to find the minimum value of a given collection of values. It is a powerful feature that can be used in various scenarios to make your code more efficient and readable.