PHP适用于foreach循环结果中的条件

I don't have much knowledge in PHP, your help appreciated.

I created a database query and foreach loop in PHP for getting data from database, Here is my foreach code:

if($user->id != 0)
{
    foreach ( $results as $result) {
        $leftday = $result->dayleft;
        $subsexp   = "-";

        if( strpos( $leftday, $subsexp ) !== false ) {
            echo "Subscription Expired<br>";
        } else {
            echo "Subscription Active<br>";
        }
    }

}

Here the result as expected:

  • Subscription Expired
  • Subscription Expired
  • Subscription Active
  • Subscription Active

But how can I show only one "Subscription Expired" text when there are no any "Subscription Active"? Now it's showing 4 times "Subscription Expired" text when all subscription expired.

If what you mean is

"When all subscriptions are expired show the message only once" then use an array to store the results (active / expired). Once you have all results stored you can process the array (if all expired do this, else do that). If you echo the resutls right away as you do now, without storing the results, you cannot act upon them, something like:

<?php

$results = [];
$results['active'] = 0;
$results['expired'] = 0;
if($user->id != 0)
{
    foreach ( $results as $result) {
        $leftday = $result->dayleft;
        $subsexp   = "-";

        if( strpos( $leftday, $subsexp ) !== false ) {
            $results['expired']++;
        } else {
            $results['active']++;
        }
    }

}    //all expired
if(0 == $results['active']){
    //do something
}

you can set two flag variable one for Expired and another for Active in for each loop increase no of active and Expired (active =active+1) (Expired =Expired+1) . you will git all active and Expired .at the just compare total result from database to total Expired if both are equal you can show only one Subscription Expired

  $TotalData=count($results);
    $active=0;
    $Expired=0;
      foreach($results as $val)
       {
       if()
       {
        $active=$active+1;
       }
       else
       {
        $Expired =$Expired+1;
       }
       }

   if($Expired==$TotalData)
   {
   echo "Subscription Expired";

   }