Ben Carey
Ben Carey

Reputation: 16968

Getting week numbers for last X weeks

I have a script that builds an array of week numbers for the last 12 weeks like so:

$week_numbers = range(date('W'), date('W')-11, -1);

However, if the current week number is 1, then this will return an array like so:

Array
(
    [0] => 1
    [1] => 0
    [2] => -1
    [3] => -2
    [4] => -3
    [5] => -4
    [6] => -5
    [7] => -6
    [8] => -7
    [9] => -8
    [10] => -9
    [11] => -10
)

But I need this array to look like this instead:

Array
(
    [0] => 1
    [1] => 52
    [2] => 51
    [3] => 50
    [4] => 49
    [5] => 48
    [6] => 47
    [7] => 46
    [8] => 45
    [9] => 44
    [10] => 43
    [11] => 42
)

Can anyone see a simple solution to this?

I have thought about doing something like this (not tested):

$current_week_number = date('W');

if($current_week_number<12){
    // Calculate the first range of week numbers (for current year)
    $this_year_week_numbers = range(date('W'), 1, -1);
    // Calculate the next range of week numbers (for last year)
    $last_year_week_numbers = range(52, 52-(11-$current_week_number), -1);
    // Combine the two arrays to return the week numbers for the last 12 weeks
    $week_numbers = array_merge($this_year_week_numbers,$last_year_week_numbers);
}else{
    // Calculate the week numbers the easy way
    $week_numbers = range(date('W'), date('W')-11, -1);
}

Upvotes: 2

Views: 2163

Answers (4)

Halcyon
Halcyon

Reputation: 57729

You can do a modulo % trick:

$week_numbers = range(date('W'), date('W')-11, -1);
foreach ($week_numbers as $i => $number) {
    $week_numbers[$i] = (($week_numbers[$i] + 52 - 1) % 52) + 1;
}
// -1 +1 is to change the range from 0-51 to 1-52

I've found that using modulo like this is often useful for date calculations, you can something similar for months, using 12.

Upvotes: 2

Alma Do
Alma Do

Reputation: 37365

Well, I think the easiest way is to create array after getting dates:

$week_numbers = array_map(function($iDay)
{
   return ($iDay+52)%52?($iDay+52)%52:52;
}, range(date('W'), date('W')-11));

-note, that you can not do just % since 52%52 will be 0 (and you want 52)

Upvotes: 1

user557846
user557846

Reputation:

one idea

$i = 1;
while ($i <= 11) {

echo date('W', strtotime("-$i week")); //1 week ago

$i++;
}

Upvotes: 6

x4rf41
x4rf41

Reputation: 5337

if you arent scared of loops you can do this:

$week_numbers = range(date('W'), date('W')-11, -1);
foreach($week_numbers as $key => $value) { if($value < 1)  $week_numbers[$key] += 52; }

Upvotes: 2

Related Questions