Illuminate\Support\Collection::mode PHP Method

mode() public method

Get the mode of a given key.
public mode ( null $key = null ) : array
$key null
return array
    public function mode($key = null)
    {
        $count = $this->count();
        if ($count == 0) {
            return;
        }
        $collection = isset($key) ? $this->pluck($key) : $this;
        $counts = new self();
        $collection->each(function ($value) use($counts) {
            $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1;
        });
        $sorted = $counts->sort();
        $highestValue = $sorted->last();
        return $sorted->filter(function ($value) use($highestValue) {
            return $value == $highestValue;
        })->sort()->keys()->all();
    }

Usage Example

 public function testWithMultipleModeValues()
 {
     $collection = new Collection([1, 2, 2, 1]);
     $this->assertEquals([1, 2], $collection->mode());
 }