BradM
BradM

Reputation: 656

php pass variable into date string

How would it be possible to pass a variable into a date string? I have the following variables:

$start_date = date('2014-01-01');
$end_date = date('2014-12-31');

But now I am adding it to a loop where the year (2014) will change each time through, and I have that new year assigned as:

$dateArr[0];

But when I try to do this it doesn't work:

$start_date = date('$dateArr[0]-01-01');
$end_date = date('$dateArr[0]-12-31');

How could I work this syntax to pass a variable into a date string?

Upvotes: 1

Views: 1516

Answers (1)

John Conde
John Conde

Reputation: 219934

Variables are not interpolated in single quote strings. Use double quotes instead:

$start_date = date("$dateArr[0]-01-01");
$end_date = date("$dateArr[0]-12-31");

FYI, this is more straight forward using DateTime():

$start_date = new DateTime("2014-01-01");
$end_date =  new DateTime("2014-12-31");

Then when it is time to increment to the next year just use the modify() method to add one year:

$start_date->modify('+1 year');
$end_date->modify('+1 year'); 

Upvotes: 3

Related Questions