Laravel 5 Collections: Calculating the Average Value of a Collection With average

Laravel 5 Collections: Calculating the Average Value of a Collection With average

Laravel 5

The average method is simply an alias of the avg method, and can be used in exactly the same way.

Signature

public function average(
    $callback = null
);

Example Use

The following example demonstrates the usage of the average method:

// Results in 12.5
collect([5, 10, 15, 20])->avg();

// Results in 12.5
collect([5, 10, 15, 20])->average();

Using average With Higher Order Messages

The average method can also be used with higher order messaging, which allows us to invoke collection methods and access object instance properties using PHP's property accessors syntax. In the reject section, we created a Product class that was used to reject all products that were not on sale.

We will take advantage of higher order messages to easily calculate the average price on a collection of Product instances:

$products = collect([
    [
        'name'   => 'Office Chair',
        'price'  => 399.99,
        'onSale' => false
    ],
    [
        'name'   => 'Desk',
        'price'  => 199.34,
        'onSale' => true
    ]
])->transform(function ($item) {
    $product = new Product;
    $product->name = $item['name'];
    $product->price = $item['price'];
    $product->onSale = $item['onSale'];

    return $product;
});

$averagePrice = $products->average->price;

After the above example has executed, the $averagePrice variable would hold the value 299.665.

Start the Discussion

Leave a comment

Subscribe to our newsletter