Passing a Variable in strtotime() function in PHP

Oneag picture Oneag · Dec 14, 2011 · Viewed 17.5k times · Source

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

Answer

samxli picture samxli · Dec 14, 2011

Use double quotes:

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