1

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?

1 Answer 1

3

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'); 
Sign up to request clarification or add additional context in comments.

1 Comment

You've made someone very very happy, you got a "Woo Hoo" ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.