How to output a value on every third result of a foreach statement in php?

前端 未结 11 1722
醉话见心
醉话见心 2021-01-04 13:37

I have a foreach statement in my app that echos a list of my database results:



        
相关标签:
11条回答
  • 2021-01-04 13:56
    <?php
    $i = 0;
    foreach($featured_projects as $fp) {
        echo '<div class="'.($i++%3 ? 'result' : 'other_class').'">';
        echo $fp['project_name'];
        echo '</div>';
    }
    ?>
    
    0 讨论(0)
  • 2021-01-04 13:57
    <?php
        $counter = 0;
    
        foreach ($featured_projects as $fp) {
            echo '<div class="result' . ($counter++ % 3 === 0 ? ' third' : '') . '">';
            echo $fp['project_name'];
            echo '</div>';
        }
    ?>
    
    0 讨论(0)
  • 2021-01-04 13:59

    You can use a counter and the modulo/modulus operator as per below:

    <?php
    
    // control variable
    $counter = 0;
    
    foreach($featured_projects as $fp) {
    
        // reset the variable
        $class = '';
    
        // on every third result, set the variable value
        if(++$counter % 3 === 0) {
            $class = ' third';
        }
    
        // your code with the variable that holds the desirable CSS class name
        echo '<div class="result' . $class . '">';
        echo $fp['project_name'];
        echo '</div>';
    }
    
    ?>
    
    0 讨论(0)
  • 2021-01-04 14:02

    What leaves your code mostly in tact would be

    <?php 
    $i = 1;
    foreach($featured_projects as $fp) {
    printf ('<div class="%s">',(($i % 3) ? "result" : "result_every_third" ));
    echo $fp['project_name'];
    echo '</div>';
    $i++;
    }
    ?>
    

    But you may want to consider using a for or while construct around "each($featured_projects)" (see http://php.net/manual/en/function.each.php) which may result in neater code.

    0 讨论(0)
  • 2021-01-04 14:03

    If the $featured_projects array is based on incremental index you could simply use the index and the modulo % operator.

    Otherwise you would have to add a counter.

    http://php.net/manual/en/language.operators.arithmetic.php

    0 讨论(0)
  • 2021-01-04 14:03
    <?php 
    foreach($featured_projects as $fp) {
        if(++$i % 3 === 0) {
            $class = ' something';
        } else {
            $class = '';
        }
        echo '<div class="result' . $class . '">';
        echo $fp['project_name'];
        echo '</div>';
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题