Seth is currently live on Twitch! Go There Now?
December 18, 2019
Advice I Wish I Could Take For Myself
Find The Last Item In A Foreach

I've always tried to find ways to do pagination or correctly display lists. So, given that I use Yii to code in PHP, I'll get an array using $table = Table::model()->findAll("status='0'"); but never realized that you can use count(); to count how many rows came back. So here would be a solution to paging.

  • $table = Table::model()->findAll("status='0' limit 10");
  • $count = count($table);
  • if($table){
  • foreach($table as $key => $value){
  • if($key==($count-1)){
  • echo "last key";
  • }
  • }
  • }

This is pretty cool, and makes pagination a lot easier. I used to do a query where I get the findAll and then I'd do a duplicate query where I do a count, which is totally a duplication of efforts and probably has increased a lot of processing time on page loads.

 Profile Picture
Comment