I'm trying to create a very basic day booking system that needs to return all dates in a range and then remove selected dates from that range. I tried the following code but realized this removes duplicates, which is fine, but I need to remove the date as well.
Can anyone suggest a good way to do this?
In the example below, I just want to see:
2022-04-03T00:00:00.000000Z
2022-04-04T00:00:00.000000Z
2022-04-05T00:00:00.000000Z
$start_date = "2022-04-01"; $end_date = "2022-04-05"; $datesToRemove = [ '2022-04-01T00:00:00.000000Z', '2022-04-02T00:00:00.000000Z' ]; $range = Carbon::parse($start_date)->toPeriod($end_date)->toArray(); $available = array_unique(array_merge($range, $datesToRemove)); return $available;
To compare, the compared values must have the same format. I decided to convert $datesToRemove to Carbon format. You can use nested loops and check using the PHP
in_array()function.$start_date = "2022-04-01"; $end_date = "2022-04-05"; $datesToRemove = [ "2022-04-01T00:00:00.000000Z", "2022-04-02T00:00:00.000000Z" ]; $range = \Carbon\Carbon::parse($start_date)->toPeriod($end_date)->toArray(); $datesToRemove2 = []; foreach($datesToRemove as $r) { $datesToRemove2[] = \Carbon\Carbon::parse($r); } $res = []; foreach($datesToRemove2 as $index => $d1) { if(in_array($d1, $range)) { unset($range[$index]); } } return $range;Output
{ "2":"2022-04-03T00:00:00.000000Z", "3":"2022-04-04T00:00:00.000000Z", "4":"2022-04-05T00:00:00.000000Z" }mean