I'm trying to loop through 6 days of week. I'd like to show the first item in the loop as today with a CSS class of 'active'. And if the day is Sunday, then for the loop to begin at 'Mon' with the 'active' class.
I've come up with the following, but not sure how to connect it all together correctly. Any clues?
$mydays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
foreach ($mydays as $day) {
if (date('D') === $day ) {
echo '<li class="active">' . $day . '</li>';
}
if (date('D') === 'Sun') {
echo '<li class="active">Mon</li>';
}
else {
echo '<li>' . $day . '</li>';
}
}
I would use the DateTime
class and the DateTime::add()
method for that:
<?php
$datetime = new \DateTime();
$listItem = array('<li class="active">', '</li>');
$i = 0;
while (true) {
if ($i === 6) break;
if ($datetime->format('N') === '7' && $i === 0) {
$datetime->add(new \DateInterval('P1D'));
continue;
}
echo $listItem[0] . $datetime->format('D') . $listItem[1];
$listItem = array('<li>', '</li>');
$datetime->add(new \DateInterval('P1D'));
$i++;
}
Basically it just start on today. If today is a Sunday it will be skipped. The first displayed day will automatically get the active class.