skip to Main Content

How do I pass successive dates if I use a loop to pass dates that are in the array? I created a simple function to solve my problem but I got stuck when I get > 1 date successive.
Code

function daySkip($date, $count=0) {
    $holidays = ["2023-06-19"];

    $MyDateCarbon = Carbon::parse($date);

    $MyDateCarbon->addWeekdays($count);

    for ($i = 1; $i <= $count; $i++) {
        if (in_array(Carbon::parse($date)->addWeekdays($i)->toDateString(), $holidays)) {
            $MyDateCarbon->addDay();
        }
    }

    return $MyDateCarbon->format("d-m-Y");
}

When I use

$input = "2023-06-16";
$addday = daySkip($input, 1);

//output 20-06-2023

My code worked. But if there is a change in the holidays array, which for example I also input data 20-06-2023 like

$holidays = ["2023-06-19", "2023-06-20"];

Then my result is still

//output 20-06-2023

How to fix that? The date I get should be

//output 21-06-2023

How do I do a proper loop to get the number of holidays that are in the array? Please advise

2

Answers


  1. I think you probably ment to loop over the $holiday array, so I changed

    for ($i = 1; $i <= $count; $i++) {
    

    To

    for ($i = 1; $i <= count($holidays); $i++) {
    

    So the code is now

    function daySkip($date, $count=0) {
        $holidays = ["2023-06-19", "2023-06-20"];
    
        $MyDateCarbon = Carbon::parse($date);
    
        $MyDateCarbon->addWeekdays($count);
    
        for ($i = 1; $i <= count($holidays); $i++) {
            if (in_array(Carbon::parse($date)->addWeekdays($i)->format('Y-m-d'), $holidays)) {
                $MyDateCarbon->addDay();
            }
        }
        // return the carbon Object, then format when received from the function call
        // that way you dont have to have the same format all the time you use this func
        return $MyDateCarbon;
    }
    $input = "2023-06-16";
    $addday = daySkip($input, 1);
    
    echo "started with $input and got " . $addday->format("d-m-Y");
    

    and the result is

    started with 2023-06-16 and got 21-06-2023
    
    Login or Signup to reply.
  2. Replace your for-loop with this. It will add a date every time the new date is in the array

    while(in_array($MyDateCarbon->toDateString(), $holidays)) {
        $MyDateCarbon->addDay();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search