How can I make this PHP lines shorter?

烈酒焚心 提交于 2020-01-11 12:06:12

问题


I have this loop at the same it will count the output:

while ($wp_query->have_posts()) : $wp_query->the_post(); $current++; $current2++;

Then to call the proper html class I need this for my design:

<div class="span4 <?php if($current == 0) { echo 'first'; } elseif($current == 1) { echo 'second'; } elseif($current == 2) { echo 'first'; } elseif($current == 3) { echo 'second'; } ?>" id="<? echo $current; ?>">

The $count starts from 0 and $count2 from 1. The output should be like this: if 0=first, 1=second, 2=first, 3=second and so forth. How can I make this expression shorter with unlimited number of $count? I hope my question is clear. Thank you for those who will help me here.


回答1:


If I understand what you are asking here, I think you want to alternate your divs with'first' and 'second' classes?

As such, you can use the % modulo operator (see http://php.net/manual/en/internals2.opcodes.mod.php)

<div class="span4 <?php echo ($current % 2 === 0 ? 'first' : 'second'); ?>" id="<? echo $current; ?>">



回答2:


If you are just using these class names for alternating CSS styles there is a much elegant way to do this using CSS3

Your HTML

<div class="span4" id="<? echo $current; ?>">

And in your css file

.span4:nth-child(even) {background: #CCC}
.span4:nth-child(odd) {background: #FFF}

else for a PHP solution the answer by Liam Wiltshire should work good.

source: CSS even and odd rules examples




回答3:


So you could use mod - best to use the full<?php tag for WordPress if that is what it is.

php test if number is odd or even

    // set up the html clips
    if($current % 2 == 0){
    $html_clips = 'first'; 
    }else{
    $html_clips = 'second'; 
    }
    if($current == 0) $html_clips = 'first';
    <div class="span4 <?php echo $html_clips ?>" id="<?php echo $current; ?>">



回答4:


try this way

<div class="span4 
 <?php if ($curent%2 == 0){ echo 'first'; } 
  else {echo 'second';}?> id="<? echo $current; ?>"> 


来源:https://stackoverflow.com/questions/33714062/how-can-i-make-this-php-lines-shorter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!