Laravel 5 Collections: Calculating the Sum of a Collection With sum

April 22, 2018 —John Koster

The sum is a simple method that returns the sum of all items in a collection. It also defines a $callback parameter which can be used to tell the sum method which values of the collection should be added together. If no items are in the collection, the sum method will return 0.

#Signature

1public function sum(
2 $callback = null
3);

#Example Use

The following code example shows the simplest way to use the sum method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 1, 2, 3, 4, 5
6]);
7 
8// 15
9$sum = $collection->sum();

After the above code has executed, the $sum variable will contain the value 15, which is indeed the sum of all the items in the collection.

The following is a more interesting example, and shows the total number of speakers at Laracon EU for the years 2013, 2014, and 2015. The number of speakers is not unique, and therefore not technically accurate:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 ['year' => '2015', 'speakers' => 12],
6 ['year' => '2014', 'speakers' => 21],
7 ['year' => '2013', 'speakers' => 10]
8 
9]);
10 
11// 43
12$totalSpeakers = $collection->sum('speakers');

After the above code has executed, the $totalSpeakers variable would contain the value 43.

The following collection also contains the number of speakers that spoke Laracon EU from 2013 to 2015, but instead of representing the speakers as number, the collection contains lists the names of the speakers.

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 [
6 'year' => '2015',
7 'speakers' => [
8 'Jeffrey',
9 'Taylor',
10 'Matt',
11 'Konstantin',
12 'Jessica',
13 'Frank',
14 'Adam',
15 'Lorna',
16 'Dries',
17 'Ben',
18 'Esther',
19 'Hannes'
20 ]
21 ],
22 [
23 'year' => '2014',
24 'speakers' => [
25 'Taylor',
26 'Ross',
27 'Erika',
28 'Konstantin',
29 'Andreas',
30 'Kayla',
31 'Matthias',
32 'Mathias',
33 'Ben',
34 'Rafael',
35 'Igor',
36 'Michelle',
37 'Adam',
38 'Xander',
39 'Wim',
40 'Mitchell',
41 'Gabriela',
42 'Matt',
43 'Frank',
44 'Hannes',
45 'Kirk'
46 ]
47 ],
48 [
49 'year' => '2013',
50 'speakers' => [
51 'Taylor',
52 'Fabien',
53 'Phill',
54 'Jordi',
55 'Kapil',
56 'Matthew',
57 'Frank',
58 'Jeffrey',
59 'Ben',
60 'Ross'
61 ]
62 ]
63]);

The total number of speakers can be counted using the sum method by passing a function as the argument to the $callback parameter. The callback function passed must define one parameter, which will be the value of the item. The following code example shows how to get the sum of all the speakers in the above collection:

1// 43
2$totalSpeakers = $collection->sum(function($value) {
3 return count($value['speakers']);
4});

After the above code has executed, the value of $totalSpeakers will be 43, just as it was in the previous example. It is important to note that the callback function should return a numerical value, and in the above example it is returning the result of the count function.

#Using sum With Higher Order Messages

Higher order messages are a concept that allows you to invoke methods on objects within a collection using property accessors syntax. The following example will use the Laracon EU collection be built in the previous section. We will create a new Conference class to represent our conferences:

The Conference Class:

1class Conference
2{
3 
4 /**
5 * The conference speakers.
6 *
7 * @var array
8 */
9 protected $speakers = [];
10 
11 /**
12 * The name of the conference.
13 *
14 * @var string
15 */
16 protected $name = '';
17 
18 /**
19 * Instantiates a new Conference instance.
20 *
21 * @param string $name The name of the conference.
22 */
23 public function __construct($name)
24 {
25 $this->name = $name;
26 }
27 
28 /**
29 * Sets the conference speakers and
30 * returns the Conference instance.
31 *
32 * @param array $speakers
33 * @return $this
34 */
35 public function withSpeakers($speakers) {
36 $this->speakers = $speakers;
37 
38 return $this;
39 }
40 
41 /**
42 * Returns the number of speakers.
43 *
44 * @return int
45 */
46 public function numberOfSpeakers()
47 {
48 return count($this->speakers);
49 }
50}

Using our new Conference class, we can utilize the transform method to convert our conference arrays into Conference object instances:

1$conferences = $collection->transform(function ($item) ) {
2 return with(new Conference($item['year']))
3 ->withSpeakers($item['speakers']);
4});

The $conferences collection will now contain Conference object instances instead of our previous arrays. Our particular implementation of Conference exposes a method numberOfSpeakers which simply returns the number of speakers at that particular conference instance.

Using Laravel's collection higher order messages, we can invoke this method to produce a sum of all conference speakers:

Calculating a Sum with Higher Order Messages:

1// Determine the number of speakers at all conferences
2// using higher order messages.
3$totalSpeakers = $conferences->sum->numberOfSpeakers();

Like before, after the above code has executed, the $totalSpeakers variable would contain the value 43.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.