Why DatePeriod instance acts like an array in foreach?

Viewed 50

Code example

$start = new DateTime();
$end = new DateTime();
$end->modify('+1 month');

$interval = new DateInterval('P1W');
$period = new DatePeriod($start, $interval, $end);

foreach($period as $i => $date){
    print "$i =>";
    var_dump($date);
}

$period is an object, not array.

Why does it act like a numbered array with 4 elements? I don't understand where they come from. I var_dump($period) and it has 6 properties and none of them is an array with 4 elements:

public 'start'
public 'current'
public 'end'
public 'interval'
public 'recurrences'
public 'include_start_date'
1 Answers

From the documentation:

A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

Class synopsis

class DatePeriod implements IteratorAggregate

It implements the iterator protocol, which allows you to iterate over it like an array.

Related