Generate the days of the current week?

Asked

Viewed 684 times

2

I need to generate the days of the current week from Sunday to Saturday and store them in a vector in the format dd/mm/aaaa, I have the following code to catch the current week:

$diaAtual = date('w'); 
$semAtual = date('Ymd', strtotime('-'.$diaAtual.' days')); 

The vector would have to stay that way:

$dias(7){
 [dom] => '13/08/2017', 
 [seg] => '14/08/2017', 
 [ter] => '15/08/2017', 
 [qua] => '16/08/2017',
 [qui] => '17/08/2017', 
 [sex] => '18/08/2017', 
 [sab] => '19/08/2017'
} 
  • The solutions didn’t help you?

2 answers

1

You can use timestamp for this...I made a quick example, but I believe I can help, instead of echo you would use the array:

echo date('d/m/Y', $timestamp)."<br>"; 

for($i=date('w');$i>=0;$i--){
   $timestamp = strtotime("-".$i." days");
  echo date('d/m/Y', $timestamp)."<br>";  
}
$fim = 7 - date('w');
for($i=0;$i<=$fim;$i++){
   $timestamp = strtotime("+".$i." days");
   echo date('d/m/Y', $timestamp)."<br>";   
}
?>

  • In case I want to use the current week with parameter, not a date.

1

The function below works like this: if it is informed some date is generated the week of the given date, if it is not informed anything is generated by the current date of the system, example:

<?php                   
    function render($date = null)
    {
        $current = is_null($date)
            ? date('w')     
            : date('w', strtotime($date));

        $now = is_null($date)
            ? strtotime('now')
            : strtotime($date);

        $week = ['dom' => '',
            'seg' => '',
            'ter' => '',
            'qua' => '',
            'qui' => '',
            'sex' => '',
            'sab' => ''];   

        $keys = array_keys($week);

        if ($current > 0)
        { 
            $now = strtotime('-'.($current).' day', $now);      
        }

        for($i = 0; $i < 7; $i++)
        {
            $week[$keys[$i]] = date('d/m/Y', 
                strtotime("+$i day", $now));            
        }
        return $week;
    }


    var_dump(render());
    var_dump(render('2017-08-06'));

Online Example

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.