rob.m rob.m - 17 days ago 6
PHP Question

How to dynamically open/close ul and li every x?

I am trying to build a php loop which generates a html navigation with years like this:

<ul>
<li>
1900
<ul>
<li>1901</li>
<li>1902</li>
</ul>
</li>
<li>
2000
<ul>
<li>2001</li>
<li>2002</li>
</ul>
</li>
</ul>


Php I am trying:

foreach (range(0, 1000, 100) as $number) { ?>
<ul>
// Here I should be checking
// if it is year 1942 or 2000 or 1080
// and place ti correctly
<?php echo $number; ?>
</ul>
<?php }


The above works, gives me a new
ul
every 100.

But I don't understand how I should set my
php
to open a new
<ul>
and
<li>
if we have "sub years" inside the century itself, also I should be checking what year is it that I am outputting in order to have it in its right
<ul>
or
<li>

Answer

I hope this is what you need:

<?php
$start_year=1900;
$end_year=2100;
for($year=$start_year;$year<=$end_year;$year++){
    if($year%10==0) //Replace 10 (for decades) with 100 (for centuries)
    {
        if($year!=$start_year){
            echo '</ul></li></ul>';
        }
        echo '<ul><li>'.$year.'<ul>';
    }
    else{
        echo '<li>'.$year.'</li>';
    }
}
?>