3

I got this:

$newcw = array_rand( range( 1, 52 ), 15 ) ;
shuffle($newcw);
$year = date("Y");
$time = mktime(0,0,0,1,1,$year) + ($newcw * 7 * 24 * 60 * 60);
$time = $time - ((date('N', $time) - 1) * 24 * 60 * 60);

$startWeek = date('D d-M-Y', $time);
$endWeek = date('D d-M-Y', $time + (6 * 24 * 60 * 60));

So basically I get a random integer which stands for calender week.

I calculate the starting day (monday) and ending day(sunday) of that calender week.

But I get following error:

Fatal error: Unsupported operand types in 88

line 88 would be this line:

$time = mktime(0,0,0,1,1,$year) + ($newcw * 7 * 24 * 60 * 60);

EDIT: I want a random integer which shall not repeats itself, that it why I am trying this method.

Jon Don
  • 81
  • 5

2 Answers2

3

If you just want a single value, use regular rand function:

//$newcw = array_rand( range( 1, 52 ), 15 ) ;
//shuffle($newcw);

$newcw = rand(1,52);

http://php.net/manual/en/function.rand.php

If however you actually need to use the other 14 values somewhere later in the script, you can just select the 1st element in the suffled array for this calculation:

$newcw = array_rand( range( 1, 52 ), 15 ) ;
shuffle($newcw);
$year = date("Y");
$time = mktime(0,0,0,1,1,$year) + ($newcw[0] * 7 * 24 * 60 * 60); //<-- note [0]

Then use the other values as required, by incrementing the key each time, eg:

some_func($newcw[1]); 

$val = $newcs[2] + 100; 
//....
another_func($newcw[14];
Steve
  • 20,703
  • 5
  • 41
  • 67
  • The thing is I want a random integer which shall not repeats itself, that it why I am trying this method – Jon Don Oct 09 '15 at 13:57
  • 1
    @JonDon Please explain - do you mean you need all 15 values in this script? If yes then just access each one by key as i demonstrate in the second paragraph. so the next value would be `$newcw[1]` – Steve Oct 09 '15 at 14:01
  • Can I access all keys at once? – Jon Don Oct 09 '15 at 14:12
  • @JonDon Well `$newcw` is an array, so it already contains all 15 values. If you want to use one after the other, just increment the key each time: `some_func($newcw[0]); $val = $newcs[1] + 100; another_func($newcw[2];` etc – Steve Oct 09 '15 at 14:40
  • Thanks could you write this in your answer so its formatted – Jon Don Oct 09 '15 at 14:54
  • @JonDon, if the answer solved your problem, you might consider accepting it. – Lajos Arpad Oct 09 '15 at 16:01
2

$newcw is array and you try to mutiply array with integer that is why you get error in this line

Robert
  • 19,800
  • 5
  • 55
  • 85
  • use rand() with modulo operator which suits more there you can also get variable from $newcw with `$newcw[rand() % count($newcw) - 1]` – Robert Oct 09 '15 at 14:03