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.
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'));
}
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'));
}
}
?>
Try this:
if( $week_value == 52 )$week_value = 0;
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;
Do modulo (%
) with 52.
That way you can assure that your week will always be less than 52.