Kyle Tozer
Kyle Tozer

Reputation: 37

Repeating an HTML element with incrementing variables

I currently have a simple html list. What I want is to repeat this list item with each repeated element having a variable that will increase by one, each time it is repeated.

The php calls that i have included in the above list item is from the Advanced Custom Field plugin on WordPress. The variable I want to change is the number inside of those php calls.

<ul>
 <li>

  <?php the_field('vendor_1_name'); ?> <!--the number is the variable that i want to increase by one with each repition-->
  <a href="http://<?php the_field('vendor_1_url'); ?>" target="_blank"/>
    <?php the_field('vendor_1_url'); ?>
  </a>

 </li>

</ul>

I have an idea of how to do this using an array, but I would love to hear other methods on how to do something like this. Thanks!

Upvotes: 0

Views: 752

Answers (2)

JCOC611
JCOC611

Reputation: 19729

<ul>
  <?php for ($z = 0; $z < $n; $z++) : ?>
  <li>
     <?php the_field('vendor_'.$z.'_name'); ?>
     <a href="http://<?php the_field('vendor_'.$z.'_url'); ?>" target="_blank">
        <?php the_field('vendor_'.$z.'_url'); ?>
     </a>
   </li>
   <?php endfor; ?>
</ul>

Where $n is the number of times it should iterate.

Upvotes: 3

Chad
Chad

Reputation: 1549

Use a for loop. If you have an array of items (are you grabbing vendors from a database?), just iterate through the array:

<?php

// fetch values and define $vendors
// using sql is highly recommended

echo "<ul>\n";

for ($i = 0; $i < count($vendors); $i++) {
    echo "<li><a href='".$vendors[$i]['vendor_url']."'>".$vendors[$i]['vendor_name']."</a></li>\n";
}

echo "</ul>\n";

?>

Note that the array would say vendor_name instead of vendor_1_name because the field is not going to have the iteration in its name.

Upvotes: 1

Related Questions