duanqi6007
duanqi6007
2016-01-14 11:48
浏览 135
已采纳

获取foreach循环后的最后一个数组索引

Hi I'm trying to find the last array of $linkNumber from my for each loop as i have an image outside the foreach loop that needs the data-slide-index to be the last array plus 1. Any help how to achieve this?

<?php $linkNumber = 0;?>  

<?php foreach ($variables as $variable){ ?>
     <img src="$variable" data-slide-index="$linkNumber++"/>
<?php } ?>
<img src="#" data-slide-index="<?php $linkNumber + 1;?>"
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • donglanfu5831
    donglanfu5831 2016-01-14 11:59
    已采纳

    If we ignore that your variables won't be printed or evaluated at all for the moment; essentially what you are doing is correct. Your problem is most of your logic isn't being executed.

    You need to explicitly echo variables and evaluations should be inside a PHP block, as follows

    <?php
    $linkNumber = 0;
    
    foreach ($variables as $variable) :
        ?>
        <img src="<?= $variable; ?>" data-slide-index="<?= $linkNumber; ?>"/>
        <?php
        $linkNumber++;
    endforeach;
    ?>
    
    <img src="#" data-slide-index="<?= $linkNumber; ?>"
    
    点赞 评论
  • duannai5879
    duannai5879 2016-01-14 12:04

    This should work:

    <?php $linkNumber = 0;?>  
    
    <?php foreach ($variables as $variable){ ?>
     <img src="$variable" data-slide-index="$linkNumber++"/>
     <?php } ?>
     <img src="#" data-slide-index="<?php echo count($variables) + 1;?>"
    
    点赞 评论
  • dongli7236
    dongli7236 2016-01-14 12:05

    Your code seems to work except for some syntax issues. Eliminating these this code works for me:

    <?php
    $linkNumber = 0;
    
    $variables = array("test", "test2");
    
    foreach ($variables as $variable){
         echo '<img src="' . $variable . '" data-slide-index="' . $linkNumber++ . '"/>' . "
    ";
    }
    echo '<img src="#" data-slide-index="' . $linkNumber . '">';
    
    ?>
    

    http://ideone.com/01cWNg

    点赞 评论

相关推荐