1

I am using the Laravel framework, I have an array of dates where I want to check if there are two same dates exist. The array is this

array:5 [▼
  0 => "2020-04-11"
  1 => "2020-04-11"
  2 => "2020-04-12"
  3 => "2020-04-13"
  4 => "2020-04-21"
]

I have written the following function to check, it works but I curious if there is any better way to achieve this because I have to extend it soon so there will be more nested loops.

private function validateFlyingDatesAreOverlapping($flyingDates)
{
    foreach ($flyingDates as $key => $datePick) {
        $datePickInstance = Carbon::parse($datePick)->startOfDay();
        foreach ($flyingDates as $index => $dateCompare) {
            $dateCompare = Carbon::parse($dateCompare)->startOfDay();
            if ($key != $index) {
                $result = $datePickInstance->eq($dateCompare);
                if ($result) {
                    return true;
                }
            }
        }
    }
    return false;
}
Danish
  • 343
  • 1
  • 8
  • 21

2 Answers2

3

You can use collection unique and count method:

$is_same_exists = !(collect($data)->count() == collect($data)->unique()->count());
TsaiKoga
  • 12,914
  • 2
  • 19
  • 28
2

If you just need to know if duplicates is exists without getting the values (your function returns boolean, so looks like this is what you need), then you can just compare the count of items in the initial array with count of unique items in array, like this:

if (count(array_unique($array)) != count($array)) {
   //duplicates is exists
}
TsaiKoga
  • 12,914
  • 2
  • 19
  • 28
Alex
  • 2,707
  • 4
  • 29
  • 42