How can JavaScript be integrated with PHP to enhance image viewing functionality on a webpage?

To enhance image viewing functionality on a webpage using JavaScript and PHP, you can create a PHP script that retrieves a list of image files from a directory and then pass this list to JavaScript for dynamic image loading and viewing.

<?php
$directory = 'images/';
$images = glob($directory . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
?>

<script>
var images = <?php echo json_encode($images); ?>;
var currentIndex = 0;

function showImage(index) {
    var img = document.getElementById('image');
    img.src = images[index];
}

function showNextImage() {
    if(currentIndex < images.length - 1) {
        currentIndex++;
        showImage(currentIndex);
    }
}

function showPreviousImage() {
    if(currentIndex > 0) {
        currentIndex--;
        showImage(currentIndex);
    }
}
</script>