0

The following code will increase/decrease week by 1: (yes, my application requires the value to be stored in a $_SESSION.

if (isset($_POST['decrease'])) {
  $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']-1);
}
else if (isset($_POST['increase'])) {
  $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']+1);
}
else {
  $week_value = ($_SESSION['sess_week'] = date('W'));
}

echo $week_value;

However I would like it to reset at week 52 (new year). How can I do this? I'm new to programming.

David
  • 1,171
  • 8
  • 26
  • 48

5 Answers5

1

You can use the date("W") function to get the week number of the current time. If it is week 1, simply set it to 1 (or 0 if you start there).

You can play around and test it out by using a mktime() as a second parameter in the date function to verify the outputs.

<?php

    if (date("W")==1)
    {
        $week_value =1;
    }
    else
    {
        if (isset($_POST['decrease'])) {
          $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']-1);
        }
        else if (isset($_POST['increase'])) {
          $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']+1);
        }
        else {
          $week_value = ($_SESSION['sess_week'] = date('W'));
        }
    }

?>
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
1
if (isset($_POST['decrease'])) {
  $week_value = $_SESSION['sess_week'] == 1 ? 52 : --$_SESSION['sess_week'];
}
else if (isset($_POST['increase'])) {
  $week_value = $_SESSION['sess_week'] == 52 ? 1 : ++$_SESSION['sess_week'];
}
else {
  $week_value = ($_SESSION['sess_week'] = date('W'));
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Thank's everyone for the fast replies. I went with @xdazz code. It worked like a charm! – David Aug 02 '12 at 08:39
1

One possibility to do this is as follows. (I took it that you meant that if the week is more than 52 it shall be 1. Additionally I added that if the week drops below 1 it shall be 52 again, thus the last week of the last year).

if (isset($_POST['decrease']))
{
     $week_value=$_SESSION['sess_week']-1;
}
else
{
     if (isset($_POST['increase']))
     {
          $week_value=$_SESSION['sess_week']+1;
     }
     else
     {
          $week_value=date('W');
     }
}

if ($week_value>52)
{
     $week_value=1;
}
else
{
     if ($week_value<1)
          $week_value=52;
}
$_SESSION['sess_week']=$week_value;
Thomas
  • 2,886
  • 3
  • 34
  • 78
0

Do modulo (%) with 52.

That way you can assure that your week will always be less than 52.

Prasanth
  • 5,230
  • 2
  • 29
  • 61
-1

Try this:

if( $week_value == 52 )$week_value = 0;
Hristo Petev
  • 309
  • 3
  • 13