John C. Derrick
John C. Derrick

Reputation: 77

How can I retrieve the output of a php foreach statement as a variable?

Proving to myself I'm still a total PHP newbie, I really could use some help. I have the following code (bottom) and it's providing me the data I need in this format:

2012-11-01;;1;;200, 2012-11-02;;1;;200, 2012-11-03;;1;;200, 2012-11-04;;1;;200, 2012-11-04;;1;;200, 2012-11-05;;1;;200, 2012-11-06;;1;;200, ...etc...

But the problem is I need the total output of the foreach statement to be set as a variable. I know I've been SO close, but I keep messing it up. How can I set a variable to have the same value as the total output of the foreach statement that still looks like the above output when echo'd out?

function getDatesBetween2Dates($startTime, $endTime) {
    $day = 86400;
    $format = 'Y-m-d';
    $startTime = strtotime($startTime);
    $endTime = strtotime($endTime);
    $numDays = round(($endTime - $startTime) / $day) + 1; // + 1
    $days = array();

    for ($i = 0; $i < $numDays; $i++) {
        $days[] = date($format, ($startTime + ($i * $day)));
    }
    return $days;
}

$days = getDatesBetween2Dates('2012-11-01', '2012-11-30');

    foreach($days as $key => $value){
    echo $value.";;1;;200,\n";
    }

Upvotes: 1

Views: 44

Answers (1)

The Alpha
The Alpha

Reputation: 146191

Something like this

$value='';
foreach($days as $key => $val){
    $value.=$val.";";
}
echo $value; // Output will be 2012-11-01;2012-11-02;2012-11-03; and more...

DEMO.

Upvotes: 1

Related Questions