0

I have a list of < li >'s but without classes, I want to make for EACH < li > a different class.. something like this

< li class="1" >
< li class="2" >
< li class="3" >

Here is the code that I have:

<ul id="tralila">
    <?php
    foreach($lists as $key=>$region)
    { 
    ?>
        <li>
            <?php  $regionLink =  "index.php?option=$option&Itemid=$listitemid&task=regions.region&rid=$region->id";
                   echo '<a href="'.$regionLink.'">'.$region->title.'</a>';?> 
        </li>
    <?php
        $location = $key+1;
    } ?>
</ul>
simont
  • 68,704
  • 18
  • 117
  • 136
Alexandru Vlas
  • 1,355
  • 3
  • 18
  • 30

3 Answers3

1

You can try:

<?php
$i = 1;
foreach($lists as $key=>$region)
{ 
?>
    <li class="<?php echo "className$i"; ?>">
        <?php  $regionLink =  "index.php?option=$option&Itemid=$listitemid&task=regions.region&rid=$region->id";
               echo '<a href="'.$regionLink.'">'.$region->title.'</a>';?> 
    </li>
<?php
    $location = $key+1;
    $i++;
} ?>

Or, instead, you could use the $key from your foreach instead of creating, and incrementing, a counter variable.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Thank you everybody. I tried nosbor's code and it worked like a charm. Thank you all!! Cheers Alex – Alexandru Vlas Mar 03 '12 at 20:56
  • 1
    +1 for a sensible answer by fixing the proposed invalid class names: http://stackoverflow.com/questions/448981/what-characters-are-valid-in-css-class-names – Treffynnon Mar 05 '12 at 09:36
0

So this is how you would do it using the key from $lists. Note I have added a prefix of li- as classes cannot start with a digit. See: Which characters are valid in CSS class names/selectors?

<ul id="tralila">
    <?php
    foreach($lists as $key=>$region)
    { 
    ?>
        <li class="<?php echo 'li-' . htmlentities($key); ?>">
            <?php  $regionLink =  "index.php?option=$option&Itemid=$listitemid&task=regions.region&rid=$region->id";
                   echo '<a href="'.$regionLink.'">'.$region->title.'</a>';?> 
        </li>
    <?php
        $location = $key+1;
    } ?>
</ul>

As all of the classes are unique I would use IDs instead of a class though.

Community
  • 1
  • 1
Treffynnon
  • 21,365
  • 6
  • 65
  • 98
-1

Something like this?:

<ul id="tralila">
    <?php
    $class_name = 0;
    foreach($lists as $key=>$region)
    { 

    ?>
        <li class="<?=++$class_name;?>">
            <?php  $regionLink =  "index.php?option=$option&Itemid=$listitemid&task=regions.region&rid=$region->id";
                   echo '<a href="'.$regionLink.'">'.$region->title.'</a>';?> 
        </li>
    <?php
        $location = $key+1;
    } ?>
</ul>
nosbor
  • 2,826
  • 3
  • 39
  • 63