Passing a Variable in strtotime() function in PHP
Solution 1
Use double quotes:
date('Y-m-d', strtotime("-$maxAge days"));
Solution 2
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;
Solution 3
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
Admin
Updated on June 21, 2022Comments
-
Admin almost 2 years
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