0

I need to assign a variable to be the output of a function that contains a loop.

Current function:

function dateRange($numberofDays){
    while($x<=$numberofDays) {
        $currentNumber = "-" . $x . " days";
        $date = DATE('Y-m-d', STRTOTIME($currentNumber));
        $theRange = $date . ",";
        $x++;
    }
    return $theRange;
}

Current result:

echo dateRange(7); // outputs a single date "2014-08-02,"

I need to return a string of dates, however it only seems to be pulling the LAST date in the function.

Looking for something like: "2014-08-08,2014-08-07,2014-08-06,2014-08-05,2014-08-04,"

1
  • Given your loop, you keep reassigning and overwriting previous values which were stored in your $theRange value. What would be required to keep adding onto the existing value until the loop is complete? Commented Aug 9, 2014 at 22:27

2 Answers 2

1

You can fix this by changing this line:

$theRange = $date . ",";

To use .= instead of =:

$theRange .= $date . ",";

The current code is overwriting the value of $theRange instead of appending to it.


EDIT: You could also use an array:

function dateRange($numberOfDays){
    $dates = array();

    for ($i = 0; $i < $numberOfDays, $i++) {
        $dates[] = date('Y-m-d', strtotime("-" . $i . " days"));
    }

    // Join the array elements together, separated by commas
    // Also add an extra comma on the end, per the desired output
    return implode(',', $dates) . ',';
}
Sign up to request clarification or add additional context in comments.

2 Comments

It also needs a line to declare $theRange initially, otherwise the first time it tries to append there is nothing to append to
Awesome - THANK YOU! Should have just asked an hour ago!
0

Currently you override the previous value of $theRange with each assignment, you need to use the string append operator ".=" and assign an initial value to $theRange, like below:

function dateRange($numberofDays){
    $theRange = "";    //added this line
    while($x<=$numberofDays) {
        $currentNumber = "-" . $x . " days";
        $date = DATE('Y-m-d', STRTOTIME($currentNumber));
        $theRange .= $date . ","; //changed this line
        $x++;
    }
    return $theRange;
}

Comments

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.