How can user experience be improved by implementing automatic loading of list items while scrolling in PHP?

Implementing automatic loading of list items while scrolling in PHP can improve user experience by reducing the need for manual pagination or clicking through multiple pages. This feature allows users to seamlessly view more content as they scroll down the page, creating a smoother and more engaging browsing experience.

<?php

// Assuming $items is an array of list items to be displayed

// Check if AJAX request is sent
if(isset($_GET['page'])){
  $page = $_GET['page'];
  $itemsPerPage = 10;
  
  // Calculate starting index for items to display
  $start = ($page - 1) * $itemsPerPage;
  
  // Get items for the current page
  $pagedItems = array_slice($items, $start, $itemsPerPage);
  
  // Output items as JSON
  echo json_encode($pagedItems);
  exit;
}

// Display initial list items
foreach($items as $item){
  echo '<div>' . $item . '</div>';
}

?>

<script>
$(document).ready(function(){
  var page = 1;
  
  $(window).scroll(function(){
    if($(window).scrollTop() + $(window).height() == $(document).height()){
      page++;
      
      // Make AJAX request to get more items
      $.get('your-php-script.php', {page: page}, function(data){
        data.forEach(function(item){
          $('#list-container').append('<div>' + item + '</div>');
        });
      });
    }
  });
});
</script>