Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically create list items from number

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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 'class="active"'; } ?>></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

>Solution :

Do it in a loop

<ul>

<?php 
for ( $i=0; $i<$count; $i++) {
    if ($i == 0) { 
        echo '<li class="active"></li>';
    } else {
        echo '<li></li>';
    }
}
?>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading