Balloon Fight
Balloon Fight

Reputation: 655

How to echo individual dates from dates array?

Right now my program echo an array of dates generated with for loop. What I'm trying to do is echo dates individually.

Initial code

 // initialize an array with your first date
    $dates = array(strtotime("+11 days", strtotime("2017-09-04")));

    for ($i = 1; $i <= 5; $i++) {// loop 5 times to get the next 5 dates

        // add 7 days to previous date in the array
        $dates[] = strtotime("+7 days", $dates[$i-1]);
    }

    // echo the results
    foreach ($dates as $date) {
        echo date("Y-m-d", $date);
        echo "<br>";
    }

Initial Output

2017-09-15
2017-09-22
2017-09-29
2017-10-06
2017-10-13

What I have tried

echo $dates[0];//print first date
echo "<br>";
echo $dates[1];//print second date

Trial Output

1505426400
1506031200

How can I achieve this?

Upvotes: 0

Views: 700

Answers (2)

mesinrusak
mesinrusak

Reputation: 1

try this

echo date("Y-m-d", ($dates[0])) . '<br>';
echo date("Y-m-d", ($dates[1])) . '<br>';

Upvotes: 0

Qirel
Qirel

Reputation: 26460

Either you need to use date() when outputting the elements as well - as they still are timestamps in the array (you don't change anything in the loop, you just print the elements), or you need to change the elements when you loop over them.

Alternative 1: Format on output

Convert from timestamp to datestring on output. This will still have timestamps in the array.

echo date("Y-m-d", $dates[0]);

Alternative 2: Alter the elements in the array

Alternatively, you can alter the value in the array when you loop it through foreach. If you pass by reference, you can change the value of the element inside the loop, by using & (which means that the variable is a reference and not a copy). This means that you now have datestrings in the array, and not timestamps.

foreach ($dates as &$date) {
    echo $date = date("Y-m-d", $date);
    echo "<br>";
}

If you pass by reference, you can now print it directly, as it will no longer contain the timestamp, since we changed it to the datestring.

echo $dates[0];

You should only adapt one of the alternatives, whichever is most suitable for your application.

Upvotes: 2

Related Questions