April 22, 2018 —John Koster
In a data set, the mode is the value that appears most often. The mode
method will return the mode of the data set contained within the collection; you may also specify a $key
to narrow which data field the collection looks at when determining the mode.
1public function mode(2 $key = null3);
In the following example we look at the most basic usage of the mode
method:
1// Create a sample collection.2$collection = collect([3 100, 200, 200, 300, 4004]);5 6// Determine the mode.7$mode = $collection->mode();
After the above code has executed, the $mode
variable would contain the value 200
.
In the following example, we will look at an example collection containing the names of departments and the number of employees within each department. We will then use the mode
method to determine the most common number of employees:
1$departments = collect([ 2 [ 3 'name' => 'Engineering & Technology', 4 'employees' => 32 5 ], 6 [ 7 'name' => 'Legal', 8 'employees' => 43 9 ],10 [11 'name' => 'Finance',12 'employees' => 3213 ],14 [15 'name' => 'Design',16 'employees' => 1717 ]18]);19 20$mode = $departments->mode('employees');
Once the above code has executed, the $mode
variable would contain the value 32
.
∎
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.