drtoclr046994545 2016-05-16 01:19
浏览 28

如何使循环内的变量在PHP其他地方可用

I have this complex code which writes the contents of an array inside a div using a loop with PHP =>

<div class="row"  >
<?php for ($b=0; $b<=($uz-1); $b++) { ?>
<a <?php if($b<($uz-1)){ 
echo "href";} ?>="<?php echo site_url('welcome/index/hamleno/'.($b+1).''); ?>">
<?php echo $hml[$b]."  "; ?></a> <?php } ?>
</div>

The problem I have is that I need to compare $b outside of the loop just inside the opening div like this=>

<div class="row <?php if( $b==$ti){echo "some-class"} ?> ">

I can't figure out a chic way; can anyone help?

  • 写回答

1条回答 默认 最新

  • dtl85148 2016-05-16 03:17
    关注

    For starters, when using a for loop and initializing a counter like $b in your example, this counter is created when the loop starts and is destroyed when the loop exits. You can't access it elsewhere, especially not before the loop creates it, as I think you want to do. This leaves you two possible solutions:

    1. Copy the value to an outside variable before the loop ends, then you can examine the value outside the loop. (after the loop only, though)

    OR

    1. Create $b beforehand, look at it before the loop, then use a while loop and manually increment $b as your counter. Since you create it outside the loop, it will still exist and can be referenced before, during and after the loop. Here's an example:

      <div class="row">
      
        <?php
           $b = 0;
      
           if ($b == $ti) { echo "some-class"; }
      
           while ($b <= ($uz-1)) 
           {
              echo '<a ';
              if ($b < ($uz-1)){ echo 'href'; }
              echo '="';
              echo site_url('welcome/index/hamleno/'.($b+1)), '">';
              echo $hml[$b], "  ", '</a>';
              ++$b;
           }
        ?>
      
      </div>
      

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法