0

I'm trying to understand the difference between while and for each. Both of these examples will work it seems like the only real difference is preference. Perhaps it is in this case but are their situations when one is objectively better than the other?

<?php $rows = get_field('repeater_field_name');
if($rows)
    {
    echo '<ul>';
    foreach($rows as $row)
    {
        echo '<li>sub_field_1 = ' . $row['sub_field_1'] . ', sub_field_2 = ' . $row['sub_field_2'] .', etc</li>';
    }
    echo '</ul>';
} ?>

VS.

<?php if( have_rows('repeater_field_name') ): ?>

    <ul>

    <?php while( have_rows('repeater_field_name') ): the_row(); ?>

        <li><?php the_sub_field('sub_field_1'); ?>,<?php the_sub_field('sub_field_1'); ?>, etc</li>

    <?php endwhile; ?>

    </ul>
  • while executes with a boolean, foreach does not – dave Jun 27 '18 at 17:54
  • 1
    To say whether or not something is "objectively better", you need to define what "better" means. If you're just talking about speed, then that's something you could test/benchmark yourself. – Patrick Q Jun 27 '18 at 17:55

2 Answers2

2

Both are looping constructs and as per you mentioned, preference is one of the main reason for choice. But sometimes its easier to think in one format than other.

For e.g. If we want to run the loop endlessly and break out based on some condition, then while would be a more expressive and readable choice.

while (true) {
  if condition {
    break;
  }
}

Also when we want to read file line by line until the end of file, while dominates:

while (($line = fgets($handle)) !== false) {
}

But sometimes for or foreach dominates cases such as looping through set of records/list.

foreach (records as key => value) {
}

Another aspect of this is, "while" is preferred over "for" when underlying loop source is about to change inside the loop.

dpattayath
  • 160
  • 5
0

This question was discussed a lot and here is the famous answer.

https://stackoverflow.com/a/12847533/4553685

Also, I make this question as duplicate

Aram Grigoryan
  • 740
  • 1
  • 6
  • 24