Skip to content
Advertisement

Use $I++ more than once in a loop

I need to use the value for $i++ in numerous places but if I do that then some fields end up skipping values and instead of being 1, 2, 3 etc. they are 1, 3, 5 and the other field has values of 2, 4, 6 etc.

<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
 <div>This number: <?php echo $i++; ?></div>
 <div>Should be the same as this one:  <?php echo $i++; ?></div>
<?php end while; ?>

It works if I create another variable but this feels like a hack.

<?php $i = 1;
      $x = 1;
?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
 <div>This number: <?php echo $i++; ?></div>
 <div>Should be the same as this one:  <?php echo $x++; ?></div>
<?php end while; ?>

Is there a better way?

Advertisement

Answer

You can do the increment as a discrete step at the end of the loop, this means you can use it in various places without wondering when you changed the value…

<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ): 
     the_row(); ?>
     <div>This number: <?php echo $i; ?></div>
     <div>Should be the same as this one:  <?php echo $i; ?></div>
     <?php $i++; ?>
<?php end while; ?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement