7

Similar to this question, but there was no answer to my specific issue.

The current date is 2011-12-14, for reference in case this question is viewed in the future.

I tried this:

$maxAge = $row['maxAge']; // for example, $row['maxAge'] == 30
$cutoff = date('Y-m-d', strtotime('-$maxAge days'));

And it returns the following value for $cutoff: 1969-12-31

And I tried this:

$maxAge = $row['maxAge']; // for example, $row['maxAge'] == 30
$cutoff = date('Y-m-d', strtotime('-' . $maxAge . ' days'));

And it returns the following value for $cutoff: 2011-03-14

How can I pass this variable successfully into the strtotime() function so that it calculates the amount of days to subtract correctly?

For example, if $maxAge == 30 and the current date is 2011-12-14, then $cutoff should be 2011-11-14

Community
  • 1
  • 1
Oneag
  • 93
  • 1
  • 1
  • 5

3 Answers3

18

Use double quotes:

date('Y-m-d', strtotime("-$maxAge days"));
samxli
  • 1,536
  • 5
  • 17
  • 28
4

Use double quotes:

$cutoff = date('Y-m-d', strtotime("-$maxAge days"));

However, if you're doing simple calculations like this, you can simply your code by not using strtotime, like so:

$date = getdate();
$cutoff = date('Y-m-d', mktime( 0, 0, 0, $date['mon'], $date['mday'] - $maxAge, $date['year']));
echo $cutoff;
nickb
  • 59,313
  • 13
  • 108
  • 143
1

You can use either a double quoted or a heredoc string in PHP for expanded variables. Single quoted and nowdoc strings do not expand variables.

http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

Sheridan Bulger
  • 1,214
  • 7
  • 9