0

I am trying to collect all the current days of the week and of the month in an array. It should be easy, but as much as I search, I can't find a solution. For example putting today as the day, the result I need is something like this:

$daysInWeek = [31,1,2,3,4,5,6];
$daysInMonth = [1,2,3,4,5,6,7,...,28];//Note here that are febrary, and need to return 28, not 31

I write this code, But I think that Carbon can make it easier:

        $weekStartDate = Carbon::now()->startOfWeek();       
        $monthStartDate = Carbon::now()->startOfMonth();

        $daysInWeek[] = $weekStartDate->day;
        for ($i=0; $i < 6; $i++) { 
            $daysInWeek[] = $weekStartDate->addDay(1)->day;
        }
        $daysInMonth[] = $monthStartDate->day;
        $lastMonthDay = Carbon::now()->month()->daysInMonth; //This return 31 days, not 28.
        for ($i=0; $i < $lastMonthDay-1; $i++) { 
            $daysInMonth[] = $monthStartDate->addDay(1)->day;
        }    
Phyron
  • 613
  • 1
  • 9
  • 25
  • 4
    `month()` is a setter, so according to my system, it's setting it to December. You can just drop that and use `Carbon::now()->daysInMonth` – aynber Feb 04 '22 at 13:33

1 Answers1

1

calculating days based on week number, check here Calculating days of week given a week number

getting the numbers of days by months is even easier with date_create and date_diff function

for ex:

<?php

$d1 = date_create(date('Y').'-'.date('m').'-01'); //current month/year
$d2 = date_create($d1->format('Y-m-t')); //get last date of the month

$days = date_diff($d1,$d2);

echo "Number of days: ". $days->days+1; //+1 for the first day

knowing the numbers of days, u can now create the necessary array for ex:

<?php

$days_arr = [];
$d = 1;
do{
    $days_arr[] = $d;
    $d++;
}while ($d <= $days->days+1);

print_r($days_arr);
zimorok
  • 326
  • 1
  • 11