fork(4) download
  1. <?php
  2.  
  3. /**
  4.  * @param itn
  5.  *
  6.  */
  7. function range_limit($current, $total, $limit = 10, $start_at = 1)
  8. {
  9. $middle = ceil($limit / 2);
  10.  
  11. $current = max($start_at, min($total, $current));
  12.  
  13. $start = $current - $middle;
  14.  
  15. $end = $middle + $current;
  16.  
  17. if ($start <= $start_at) {
  18. $start = $start_at;
  19. $end = $limit;
  20.  
  21. } elseif ($end >= $total) {
  22. $end = $total;
  23. $start = $total - $limit;
  24. }
  25.  
  26. for ($i = $start; $i <= $end; $i++) yield $i;
  27. }
  28.  
  29.  
  30. $limit = 10;
  31.  
  32. $total_pages = 55;
  33.  
  34.  
  35. foreach(range_limit(1, $total_pages, $limit) as $page) {
  36. echo $page == 1 ? " [$page] " : " $page ";
  37. }
  38.  
  39. echo "\n";
  40.  
  41. foreach(range_limit(2, $total_pages, $limit) as $page) {
  42. echo $page == 2 ? " [$page] " : " $page ";
  43. }
  44.  
  45. echo "\n";
  46.  
  47. foreach(range_limit(33, $total_pages, $limit) as $page) {
  48. echo $page == 33 ? " [$page] " : " $page ";
  49. }
  50.  
  51. echo "\n";
  52.  
  53. foreach(range_limit(40, $total_pages, $limit) as $page) {
  54. echo $page == 40 ? " [$page] " : " $page ";
  55. }
Success #stdin #stdout 0.02s 23736KB
stdin
Standard input is empty
stdout
 [1]  2  3  4  5  6  7  8  9  10 
 1  [2]  3  4  5  6  7  8  9  10 
 28  29  30  31  32  [33]  34  35  36  37  38 
 35  36  37  38  39  [40]  41  42  43  44  45