Foreach最后一项有条件

foreach ($orderItems as $item) {
    if ($item->isNotCancelled()) {
        echo 'ITEM....<br />';
        // if last NOT CANCELLED item:
        echo '<strong>ITEM....</strong><br />';
    } else {
        // ignored completely
    }
}

I need to add <strong> arround the last item which did not get cancelled... I know how to check the last item of an array or iterator, but with the condition in the if case, how'd you do this?

Will I need 2 loops?


Update & Solution: I solved this by reversing the logic and to find the first item rather than the last.

I'll keep the question up if someone wants to comment or answer anyways.

Can you try this,

    $coun = count($orderItems);
    $i=1;
    foreach ($orderItems as $item) {
        if ($item->isNotCancelled()) {
            echo 'ITEM....<br />';
            // if last NOT CANCELLED item:

        }else {
          // ignored completely
       }
         if($i==($coun-1))
            echo '<strong>ITEM....</strong><br />';
        $i++;
    }

try this:

$i=0;
$counter=0;
foreach ($orderItems as $item) {
    if ($item->isNotCancelled()) {
       $counter=$i;
   }
  $i++;
}
 $i=0;
  foreach ($orderItems as $item) {
    if ($item->isNotCancelled()) {
      if( $counter==$i){
      echo "<strong>".$item."</strong></br>"
     }
   }
  $i++;
}

what about this?

$lastNonCancelledItem = null;
foreach ($orderItems as $item) {
    if ($item->isNotCancelled()) {
        echo 'ITEM....<br />';
        $lastNonCancelledItem = $item;
    } else {
        // ignored completely
    }
}

echo '<strong>' $lastNonCancelledItem; //profit

If display these items is a complex task that you do not wish to repeat in 2 places make some sort of function to display the item

$lastNonCancelledItem = null;
foreach ($orderItems as $item) {
    if ($item->isNotCancelled()) {
        $view->showItem($item);
        $lastNonCancelledItem = $item;
    } else {
        // ignored completely
    }
}

echo $view->showItem($lastNonCancelledItem, TYPE_STRONG); //profit (or whatever)