Looping through weekdays, is there a better way?

Hi all this is more of a code review question. But it would help me immensely if someone could explain how to loop the following code to be more DRY. Particularly looking at this code:

Is there an easier way of doing this?

<?php echo page('opening')->Monday()->kt() ?>
<?php echo page('opening')->Tuesday()->kt() ?>
<?php echo page('opening')->Wednesday()->kt() ?>
<?php echo page('opening')->Thursday()->kt() ?>
<?php echo page('opening')->Friday()->kt() ?>
<?php echo page('opening')->Saturday()->kt() ?>
<?php echo page('opening')->Sunday()->kt() ?>

My panel setup

The results currently look like this:

Closed

11-19

11-19

11-19

11-19

11-16

11-17

Im really sorry if this doesnt belong here, in which case I will remove this post.

Appreciate all help. Thank you!

I think that’s an interesting thing to discuss – answering your last paragraph…

Do the fields have to be called “Monday”, “Tuesday”, …? If you’d call them “weekday1”, “weekday2”, … you could simply loop over them.
Keeping the weekdays as words you would probably need an array with the weekdays for the loop. That would at least be a bit DRYer.

But I’m sure there are some better ideas.

Thanks for the quick reply! Interesting thought. The arrays dont need to be unique. Im sure theres a better way as well!

That’s what I meant:

$days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
foreach($days as $day) {
    if($page->$day()->isNotEmpty()) {
        echo $page->$day();
    }
}

Thanks for the code snipped. It worked as advertised :slight_smile:

Heres what I ended up doing for others who might stumble upon similar challenges

<?php $days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); ?>
<ul>
<?php foreach($days as $day):  ?>
    <?php if(page('opening')->$day()->isNotEmpty()): ?>

          <li>
            <?php echo $day; ?>
            <?php echo page('opening')->$day(); ?>
          </li>

    <?php endif ?>
<?php endforeach ?>
</ul>
2 Likes