Home > database >  Dynamically create list items from number
Dynamically create list items from number

Time:11-09

I have a PHP testimonial script that is pulling it's images and text from WordPress. I have everything working except for one thing, which is the pagination. Right now, the script returns a list and the amount of li's are hard-coded. However, if I modify the amount of testimonials from 4 to 5, I also have to modify the amount of li's from 4 to 5 or the everything stops working completely. This does not work so good in a dynamic envirnoment like WordPress.

What I was thinking was using a number, but I don't know if this is possible. I can retrieve the amount of testimonials I have, and I know this is half the battle. What I wanted to do is echo that amount of li's.

My code looks like:

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

I already added some code to dynamically add an active class to the first li:

<ul>
    <li <?php if ($count == 1) { echo ''; } ?>></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

The $count variable is being specified in the actual testimonials script and is counting the amount of li's, this helps me start my active class on the right li. I know I'm close, that's 95% of it, I just don't know how to connect the two dot's and say if my number is 4 then generate 4 li's. Does that make sense?

I was thinking I could do something like:

<ul>
      <?php while($count) { echo "<li></li>"; } ?>
</ul>

but I get a 500 error when I try that, any ideas or suggestions?

Thanks,
Josh

CodePudding user response:

Do it in a loop

<ul>

<?php 
for ( $i=0; $i<$count; $i  ) {
    if ($i == 0) { 
        echo '<li ></li>';
    } else {
        echo '<li></li>';
    }
}
?>
</ul>
  • Related