Home  >  Article  >  Backend Development  >  PHP adds different classes to the li tag

PHP adds different classes to the li tag

WBOY
WBOYOriginal
2016-09-19 09:16:261472browse

......

foreach ($images as $imgUrl){

<code>  echo '<li class="right"></li>'; 
  </code>

}

Part of the code was omitted earlier, and the output from the above is as follows (I output three li):



  • What I want to achieve is this:



  • That is, the first class in the list is "left" and the other classes are right.

    Reply content:

    ......

    foreach ($images as $imgUrl){

    <code>  echo '<li class="right"></li>'; 
      </code>

    }

    Part of the code was omitted earlier, and the output from the above is as follows (I output three li):



  • What I want to achieve is this:



  • That is, the first class in the list is "left" and the other classes are right.

    If your $images is an index array, and the index starts from 0, use the following method

    <code class="php"><?php
    foreach ($images as $index=>$imgUrl) {
        $class = 0===$index ? "left" : "right";
        echo '<li class="' . $class . '"></li>';
    
    }</code>

    If your $imagesarray does not meet the above conditions, you can use the following method to achieve it:

    <code class="php"><?php
    foreach ($images as $imgUrl) {
        $class = empty($class) ? "left" : "right";
        echo '<li class="' . $class . '"></li>';
    }</code>

    This output method is more troublesome. Logical processing and page display are coupled together. You can try using smarty template engine

    Just make the judgment in foreach

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn