如何使循环内的变量在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?

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>