Home > Article > Backend Development > PHP adds different classes to the li tag
......
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.
......
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 $images
array 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