In PHP, what are some efficient ways to handle navigation between images in a gallery based on categories?

When navigating between images in a gallery based on categories in PHP, one efficient way to handle this is by using a combination of PHP and HTML to dynamically generate the gallery based on the selected category. This can be achieved by storing the images and their corresponding categories in an array, and then using PHP to filter and display only the images that belong to the selected category.

<?php
// Define an array of images with their corresponding categories
$images = array(
    array('image' => 'image1.jpg', 'category' => 'nature'),
    array('image' => 'image2.jpg', 'category' => 'nature'),
    array('image' => 'image3.jpg', 'category' => 'animals'),
    array('image' => 'image4.jpg', 'category' => 'animals'),
);

// Get the selected category from the URL parameter
$category = isset($_GET['category']) ? $_GET['category'] : 'all';

// Filter the images based on the selected category
$filteredImages = ($category == 'all') ? $images : array_filter($images, function($img) use ($category) {
    return $img['category'] == $category;
});

// Display the images
foreach ($filteredImages as $img) {
    echo '<img src="' . $img['image'] . '" alt="' . $img['category'] . '">';
}
?>