<?php
function iterateOverIt($iterable) {
// First foreach acts like a guard condition
foreach ($iterable as $_) {
// Pre-processing:
echo "<ul>\n";
// Real looping, this won't start a *NEW* iteration process but will continue the one started above:
foreach ($iterable as $item) {
echo "<li>", $item instanceof DateTime ? $item->format("c") : (
isset($item["col"]) ? $item["col"] : $item
), "</li>\n";
}
// Post-processing:
echo "</ul>\n";
break;
}
}
// Empty array
iterateOverIt([]);
iterateOverIt([1, 2, 3]);
// Empty generator
iterateOverIt(function () : Generator {
return;
yield;
});
iterateOverIt((function () : Generator {
yield 4;
yield 5;
yield 6;
})());
// Class with no public properties
iterateOverIt(new stdClass());
iterateOverIt(new class { public $a = 7, $b = 8, $c = 9;});
/*
$db = mysqli_connect("localhost", "user", "pass", "db");
// Empty resultset
iterateOverIt($db->query("SELECT 0 FROM DUAL WHERE false"));
iterateOverIt($db->query("SELECT 10 AS col UNION SELECT 11 UNION SELECT 12"));
*/
// DatePeriod generating no dates
iterateOverIt(new DatePeriod(new DateTime("2020-01-01 00:00:00"), new DateInterval("P1D"), new DateTime("2020-01-01 00:00:00"), DatePeriod::EXCLUDE_START_DATE));
iterateOverIt(new DatePeriod(new DateTime("2020-01-01 00:00:00"), new DateInterval("P1D"), 3, DatePeriod::EXCLUDE_START_DATE));
- Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.31, 7.3.33, 7.4.0 - 7.4.25, 7.4.27 - 7.4.33, 8.0.0 - 8.0.12, 8.0.14 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.27, 8.3.0 - 8.3.15, 8.4.1 - 8.4.2
- <ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<ul>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
<ul>
<li>2020-01-02T00:00:00+01:00</li>
<li>2020-01-03T00:00:00+01:00</li>
<li>2020-01-04T00:00:00+01:00</li>
</ul>
- Output for 7.3.32, 7.4.26, 8.0.13
- <ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<ul>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
<ul>
<li>2020-01-02T00:00:00+00:00</li>
<li>2020-01-03T00:00:00+00:00</li>
<li>2020-01-04T00:00:00+00:00</li>
</ul>
preferences:
131.34 ms | 408 KiB | 5 Q