skip to Main Content

i have two date :
$from = 2022-11-01
$to = 2022-11-05

now , i wanna create a array like this :
$date = [‘2022-11-01′,’2022-11-02′,’2022-11-03′,’2022-11-04′,’2022-11-05’]

and now check ‘2022-11-03’ is exist in $date array or not.

alrady use :
$date = CarbonCarbonPeriod::create($from, $to);

if(in_array('2022-11-03', $date)){
    echo "Got it";
}

#But Still not Work

3

Answers


  1. You can just check if the CarbonPeriod contains the date you check:

    $from = '2022-11-01';
    $to = '2022-11-05';
    $date = CarbonCarbonPeriod::create($from, $to);
    if ($date->contains('2022-11-03')) {
        echo 'Got it';
    }
    
    Login or Signup to reply.
  2. Based on the question it could be that you aren’t using parse method to parse dates, so this could be the problem.

            $from = "2022-11-01";
            $to = "2022-11-05";
            $dates = CarbonPeriod::create(
                Carbon::parse($from),
                Carbon::parse($to),
            );
            $dateArray = [];
            foreach ($dates as $date) {
                $dateArray[] = $date->toDateString();
            }
    

    Here, $dateArray provides you with the dates array.

    Furthermore the if section works correctly for the above solution:

    if(in_array('2022-11-03', $date)){
        echo "Got it";
    }
    
    Login or Signup to reply.
  3. It was asked for a solution with CarbonPeriod. However, if you only want to check if a date is between $from and $to, between is the better choice.

    $from = "2022-11-01";
    $to = "2022-11-05";
    $check = "2022-11-03";
    if(Carbon::parse($check)->between($from,$to)){
      echo $check.' is between '.$from.' and '.$to;
    } else {
      echo $check.' is not between '.$from.' and '.$to;
    }
    

    Try Carbon

    If the data is all in the format yyyy-mm-dd, a simple string comparison is sufficient.

    $from = "2022-11-01";
    $to = "2022-11-05";
    $check = "2022-11-03";
    if($from <= $check AND $check <= $to) {
      echo $check.' is between '.$from.' and '.$to;
    } else {
      echo $check.' is not between '.$from.' and '.$to;
    }
    

    Demo: https://3v4l.org/A1IBh

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search