Passing a variable in strtotime () function in PHP

Like this question , but there was no answer to my specific problem.

The current date is 2011-12-14, for reference, if this issue is considered in the future.

I tried this:

$maxAge = $row['maxAge']; // for example, $row['maxAge'] == 30 $cutoff = date('Ym-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('Ym-d', strtotime('-' . $maxAge . ' days')); 

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

How to successfully pass this variable to the strtotime() function so that it calculates the number 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

+4
source share
3 answers

Use double quotes:

 date('Ym-d', strtotime("-$maxAge days")); 
+14
source

Use double quotes:

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

However, if you do simple calculations like this, you can just use your code without using strtotime, for example:

 $date = getdate(); $cutoff = date('Ym-d', mktime( 0, 0, 0, $date['mon'], $date['mday'] - $maxAge, $date['year'])); echo $cutoff; 
+4
source

You can use either a double quote or the heredoc string in PHP for extended variables. Single quotes and nowdoc strings do not expand variables.

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

+1
source

Source: https://habr.com/ru/post/1386362/


All Articles