PHP: Echo out only the first N of array?

I have an array of images to echo out for a photo gallery.

I want to only echo out the first 9 images in the gallery (assuming the gallery has more than 9). How do you do this in PHP?

https://www.php.net/manual/en/function.array-slice.php

1 Like

I would also Google Pagination

Here’s a small example

// Sample data array
$data = array(
    "item 1",
    "item 2",
    "item 3",
    "item 4",
    "item 5",
    "item 6",
    "item 7",
    "item 8",
    "item 9",
    "item 10"
);

// Pagination parameters
$page = isset($_GET['page']) ? $_GET['page'] : 1; // Current page number
$perPage = 9; // Number of items to display per page

// Calculate offset and limit for current page
$offset = ($page - 1) * $perPage;
$limit = $perPage;

// Get items for current page
$items = array_slice($data, $offset, $limit);

// Display items
foreach ($items as $item) {
    echo $item . "<br>";
}

// Display pagination links
$totalPages = ceil(count($data) / $perPage); // Total number of pages
for ($i = 1; $i <= $totalPages; $i++) {
    echo '<a href="?page=' . $i . '">' . $i . '</a> ';
}