How to create rating system using for loop in php yii2

     

I am working a project where i need rating system. I use kartik widget to rate but now i need some code to show rates. total stars 5 if a user get 4 star then 4 stars will be filled and one star will be empty. I did it on custom writing and I need some efficient code.


public static function rate($rate)  {   if (!is_null($rate)) {
if ($rate == 0){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 1 && $rate < 1.5){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 1.5 && $rate < 2){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 2 && $rate < 2.5){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 2.5 && $rate < 3){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 3 && $rate < 3.5){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 3.5 && $rate < 4){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 4 && $rate < 4.5){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 4.5 && $rate < 5){   echo "";   echo "";   echo "";   echo "";   echo "";   }   if ($rate >= 5){   echo "";   echo "";   echo "";   echo "";   echo "";   }  }  else  {   echo "Not Yet rated";  }  }  

How can i do this same work using loop

  
"
answer1
  
  

Try something like this:


public static function rate($rate)  {   if (!is_null($rate)) {    $rate_int = $rate/0.5;   for($i=1; $i<=floor($rate); $i++){   echo "";   }
if(($rate_int % 2) == 0) {   for($i=1; $i<=5-$rate; $i++) {   echo "";   }   }    else    {   echo "";   for($i=1; $i<=5-($rate+1); $i++){   echo "";   }   }   }   else   {   echo "Not Yet rated";   }  }  
  
  
answer2
  
  

assuming you have a collection of users model names $userModels and in this model you have a field name $rate for rate   you could invoke your static function


foreach( $userModels as $key => $value){   YourClass::rate($value->rate);
}