How can the issue of inconsistent IDs due to image deletions be addressed when implementing a next and back navigation feature in a PHP gallery?

Issue: When images are deleted from the gallery, the IDs assigned to each image become inconsistent, causing errors in the next and back navigation feature. To address this, we can dynamically adjust the IDs based on the available images when navigating through the gallery.

// Get the list of available images
$images = glob('path/to/images/*');

// Get the current image ID
$currentId = isset($_GET['id']) ? $_GET['id'] : 0;

// Adjust the current ID if it exceeds the available images
if ($currentId >= count($images)) {
    $currentId = count($images) - 1;
}

// Adjust the current ID if it is negative
if ($currentId < 0) {
    $currentId = 0;
}

// Display the current image
echo '<img src="' . $images[$currentId] . '" />';

// Display navigation links
echo '<a href="?id=' . ($currentId - 1) . '">Previous</a>';
echo '<a href="?id=' . ($currentId + 1) . '">Next</a>';