Skip to content
Advertisement

Get previous week number from php week number

I currently need to get the previous week from a variable that passes a php week number so if it is week 13 I will get week 12.

The problem I am facing is that if I just minus 1 from the original number if I am in week 1 it will return week 0 unless I create an if statement ie:

if($week==1)
{
    $prev_week=52;
    $prev_year=$year-1;
}

This is assuming that php counts the weeks from 1 and not 0. This seems a bit clumsy and I was thinking there may be a better way of doing this utilizing PHP’s many date and time functions.

Advertisement

Answer

I think I could be over complicating the problem – basically I need to obtain results from the database that appear in the previous weeks from the selected week therefore if there is a possibility of 54 weeks in a year all I really need to do is:-

 if($week==1)
 {
    $year_minsued=$year-1;
    $week_minused=54;
 }
 else
 {
    $week_minused=$week-1;
    $year_minused=$year;
 }

My select statement can then read:

SELECT SUM(post_price), SUM(total_price) FROM
database_table
WHERE client_id='$account_no'
AND
   (year<='$year_minused' AND week<='$week_minused')

I have not tested this as yet but thinks it should do the job.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement