Home > OS >  How to remove values from an array in Laravel
How to remove values from an array in Laravel

Time:04-16

I am trying to make a really basic day booking system and need to return all dates within a range, and then remove selected dates from that range. I tried the following code but realised that will remove duplicates which is fine, but I also need that date to be removed too.

Can anyone suggest a good way of doing this?

In the below example I am just hoping 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;

CodePudding user response:

To compare it is necessary to have the compared values in the same format. I decide to morph the $datesToRemove to Carbon format. The you can use to nested loops and check with 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"
}

Means that

  • Related