How can the use of arrays in PHP be optimized for creating a pagination feature in a gallery?

When creating a pagination feature for a gallery in PHP using arrays, it's important to optimize the array manipulation to efficiently handle large datasets. One way to achieve this is by using array slicing to only fetch and display a subset of images per page, rather than loading the entire gallery array at once. This can help improve performance and reduce memory usage.

// Sample code for creating pagination feature in a gallery using optimized array slicing

// Gallery array containing all images
$gallery = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg', 'image10.jpg');

// Pagination variables
$items_per_page = 4;
$page_number = isset($_GET['page']) ? $_GET['page'] : 1;
$start_index = ($page_number - 1) * $items_per_page;
$end_index = $start_index + $items_per_page;

// Slice the gallery array to display images for the current page
$paginated_gallery = array_slice($gallery, $start_index, $items_per_page);

// Display images for the current page
foreach ($paginated_gallery as $image) {
    echo '<img src="' . $image . '" alt="Image">';
}

// Pagination links
$total_pages = ceil(count($gallery) / $items_per_page);
for ($i = 1; $i <= $total_pages; $i++) {
    echo '<a href="?page=' . $i . '">' . $i . '</a> ';
}