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;
}
1

2 Answers 2

3

You can use collection unique and count method:

$is_same_exists = !(collect($data)->count() == collect($data)->unique()->count());
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.